• Flask之初始


    一、简介

    Flask是一个基于Python实现的Web开发‘微’框架

    官方文档: http://flask.pocoo.org/docs/0.12/
    中文文档: http://docs.jinkan.org/docs/flask/

    Flask和Django一样,也是一个基于MVC设计模式的Web框架

    Flask依赖三个库
      Jinja2 模板引擎
      Werkzeug WSGI工具集
      Itsdangerous 基于Django的签名模块。

    二、hello Flask

    1、新建项目

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return 'Hello Flask'
        
    if __name__ == '__main__':
        app.run()

    2、参数配置

    在启动的时候还可以添加参数,在run()中

      debug 是否开启调试模式,开启后修改过python代码会自动重启

      threaded 是否开启多线程

      port 启动指定服务器的端口号

      host 主机,默认是127.0.0.1,指定为0.0.0.0代表本机所有ip

    3、代码结构

    static 静态资源文件

    templates 模板文件

    默认两个都可以直接使用

    直接使用相对路径就好

    模板渲染

    render_template()

    其实也是分为两个过程,加载和渲染

    可使用template = Template(“<h2>呵呵</h2>”)

    template.render()

    静态使用,相当于反向解析

    url_for(’static’,filename=‘hello.css’)

    三、项目结构  

    flask_01     # 项目总目录

        ├── App    # APP

        │   ├── ext.py   # 第三方扩展库(数据库等)

        │   ├── __init__.py    #APP的初始化文件,创建Flask对象,加载配置,初始化第三方库,初始化路由

        │   ├── models.py   # model类, 可以封装成包的形式

        │   ├── settings.py   # 项目配置文件,包括环境的配置以及数据库的配置

        │   ├── templates    # 模板文件夹

        │   │   └── h1.html

        │   └── views     # 视图函数的包

        │       ├── first.py    

        │       └── __init__.py     视图初始化,注册路由

        ├── manager.py    # 项目入口文件

        └── migrations    #数据库迁移生成

            ├── alembic.ini

            ├── env.py

            ├── README

            ├── script.py.mako

            └── versions

                └── 5f72fb96463a_.py

    1、manager

    import os
    
    from flask_migrate import MigrateCommand
    from flask_script import Manager
    
    from App import create_app
    
    env = os.environ.get("FLASK_ENV", "develop")
    
    app = create_app(env)
    
    manager = Manager(app=app)
    manager.add_command('db', MigrateCommand)
    
    
    if __name__ == '__main__':
        manager.run()

    2、APP/init.py

    from flask import Flask
    
    from App.ext import init_ext
    from App.settings import envs
    from App.views import init_view
    
    
    def create_app(env):
        app = Flask(__name__)
    
        # 加载配置
        app.config.from_object(envs.get(env))
    
        # 初始化第三方扩展库
        init_ext(app)
    
        # 初始化路由
        init_view(app=app)
    
        return app

    3、APP/ext.py

    from flask_bootstrap import Bootstrap
    from flask_migrate import Migrate
    from flask_session import Session
    from flask_sqlalchemy import SQLAlchemy

    db = SQLAlchemy()
    migrate = Migrate()


    def init_ext(app):
      db.init_app(app)
      migrate.init_app(app, db)
      Session(app)
      

    4、APP/models.py

    from App.ext import models

    5、APP/settings.py

    import os
    
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    def get_db_uri(dbinfo):
    
        engine = dbinfo.get("ENGINE") or "sqlite"
        driver = dbinfo.get("DRIVER") or "sqlite"
        user = dbinfo.get("USER") or ""
        password = dbinfo.get("PASSWORD") or ""
        host = dbinfo.get("HOST") or ""
        port = dbinfo.get("PORT") or ""
        name = dbinfo.get("NAME") or ""
    
        return "{}+{}://{}:{}@{}:{}/{}".format(engine, driver, user, password, host, port, name)
    
    
    class Config:
    DEBUG = False
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SECRET_KEY = "Rockdafafafafafa"
    # 将session存储在redis中
    SESSION_TYPE = "redis"
    REDIS_HOST = "123.56.243.64"
    REDIS_PORT = "6379"
    REDIS_DB = 0
    # session长期有效,则设定session生命周期,整数秒
    ERMANENT_SESSION_LIFETIME = 24 * 60 * 60
    # 是否强制加盐,混淆session
    SESSION_USE_SIGNER = True
    # sessons是否长期有效,false,则关闭浏览器,session失效
    SESSION_PERMANENT = False
    SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
    SESSION_COOKIE_SECURE = True
     
    
    
    class DevelopConfig(Config):
    
        DEBUG = True
    
        dbinfo = {
            "ENGINE": "mysql",
            "DRIVER": "pymysql",
            "USER": "root",
            "PASSWORD": "1",
            "HOST": "localhost",
            "PORT": "3306",
            "NAME": "RESTful"
    
        }
    
        SQLALCHEMY_DATABASE_URI = get_db_uri(dbinfo)
    
    
    class TestConfig(Config):
        TESTING = True
        dbinfo = {
            "ENGINE": "mysql",
            "DRIVER": "pymysql",
            "USER": "root",
            "PASSWORD": "2",
            "HOST": "localhost",
            "PORT": "3306",
            "NAME": "RESTful"
    
        }
    
    
        SQLALCHEMY_DATABASE_URI = get_db_uri(dbinfo)
    
    
    class StagingConfig(Config):
    
        dbinfo = {
            "ENGINE": "mysql",
            "DRIVER": "pymysql",
            "USER": "root",
            "PASSWORD": "3",
            "HOST": "localhost",
            "PORT": "3306",
            "NAME": "RESTful"
    
        }
    
        SQLALCHEMY_DATABASE_URI = get_db_uri(dbinfo)
    
    
    class ProductConfig(Config):
    
        dbinfo = {
            "ENGINE": "mysql",
            "DRIVER": "pymysql",
            "USER": "root",
            "PASSWORD": "1",
            "HOST": "localhost",
            "PORT": "3306",
            "NAME": "RESTful"
        }
    
        SQLALCHEMY_DATABASE_URI = get_db_uri(dbinfo)
    
    
    envs = {
        "develop": DevelopConfig,
        "testing": TestConfig,
        "staging": StagingConfig,
        "product": ProductConfig,
        "default": DevelopConfig
    }

    6、APP/views/__init__.py

    from App.views.first import blue
    
    
    def init_view(app):
        app.register_blueprint(blue)

    7、APP/views/first.py

    from flask import Blueprint, render_template
    
    blue = Blueprint('app', __name__)
    
    
    @blue.route('/')
    def hi():
        return render_template('h1.html', msg='这天气适合睡觉')
  • 相关阅读:
    Hdu 1257最少拦截系统
    删除mysql__转
    sql 入门的小例子熟悉一下_这可是一个转转转贴 :)
    header 用法_转
    java_json 转换 文件在file中
    javascript_php 正则匹配 转
    mysql 忘记密码转_kinghu
    php 通用下载
    明天就是新年开始
    翻译 有助于程序命名
  • 原文地址:https://www.cnblogs.com/huiyichanmian/p/12274260.html
Copyright © 2020-2023  润新知