• Flask 简单使用


    一、flask介绍

    flask是一个轻量级的web框架,可快速的搭建程序。适用于简单的程序。

    二、对比Django组件

    1 Django:无socket、中间件、路由系统、视图(CBV,FBV)、 模板、ORM、cookie、Session、Admin、Form、缓存、信号、序列化....
    2 Flask:无socket、中间件(扩展)、路由系统、视图(CBV)、第三方模板(jinja2)、cookie、Session(很弱)

    三、WSGI

    web服务网关接口协议(WSGI),功能为创建Socket,监听请求转发请求。

    Flask依赖werkzeug模块实现WSGI协议

    from werkzeug.wrappers import Request,Response
    from werkzeug.serving import run_simple
    
    @Request.application
    def hello(request):
        return Response('Hello world!')
    
    if __name__ == '__main__':
        run_simple('localhost','4000',hello)
    


    四、Flask简单实现用户登录

    flask_practice/example.py  

    from flask import Flask,render_template,request,redirect,session
    
    app = Flask(__name__,template_folder='templates',static_url_path='/static')
    # template_folder='templates' 指定templates目录名,默认为templates
    # static_url_path='/static'  影响页面静态文件前缀路径
    # root_path=''         指定当前目录位置路径,默认为当前目录
    
    
    app.secret_key = 'xxxxxxddddddffffffffff'   
    # flask的session没有持续存储到数据库或其他空间,而是生成随机字符串作为session
    # 之后将session加密放到cookie中的发送到客户端浏览器,secret_key对session加密同时的加言后,加大了反解难度
    
    
    @app.route('/login',methods=['GET',"POST"])  # 创建路由映射,并保存路由关系,methods指定请求的方法
    def login():
        if request.method == 'GET':
            return render_template('login.html')
        else:
            user = request.form.get('user')
            pwd = request.form.get('pwd')
            if user == 'alex' and pwd == '123':
                session['user_info'] = user
                return redirect('/index')
            else:
                return render_template('login.html',msg='用户名或密码错误')  # msg='用户名或密码错误'传递至前端
    
    @app.route('/index',methods=['GET'])      # 路由系统的本质,是将url和函数封装到rule对象,添加到MAP中
    def index():
        if not session.get('user_info'):
            return redirect('login')
        return '欢迎登录'
    
    if __name__ == '__main__':
      # 启动程序,监听用户请求
      # 一旦请求到来执行app.__call__方法
      # 封装用户请求
      # 进行路由匹配函数
        app.run()  
    

     flask_practice/templates/login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>login</h1>
        <form method="post">
            <input type="text" name="user">
            <input type="text" name="pwd">
            <input type="submit" value="登录">{{msg}}
        </form>
        <img style=" 300px;height: 200px" src="/static/img/ooo.jpg" alt="">
    </body>
    </html>
    
  • 相关阅读:
    文件目录T位
    改变文件权限的用户身份
    改变进程打开文件默认权限检查方式
    新建文件的UID和GID
    进程的用户ID
    centos7使用无线wifi连接
    2.8. 创建 NSManagedObject 的子类 (Core Data 应用程序实践指南)
    2.7. 属性的各种设置选项(Core Data 应用程序实践指南)
    2.6. 类型(Core Data 应用程序实践指南)
    2.5. Integer 16 、Integer 32、Integer 64(Core Data 应用程序实践指南)
  • 原文地址:https://www.cnblogs.com/yunweixiaoxuesheng/p/8342559.html
Copyright © 2020-2023  润新知