美文网首页
python-Flask(模块)

python-Flask(模块)

作者: SmallPot_Yang | 来源:发表于2018-03-30 10:59 被阅读0次

    常用模块与用法

    [TOC]

    Flask(主app)

    from flask import Flask     # 用于实例app = Flask(__name__)
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
        
    if __name__ =  '__main__':
        app.run(debug=True)
    

    redirect(重定向),url_for(url反转)

    from flask import redirect  # 页面重定向
    from flask import url_for   # url反转
    @app.route('/url/')
    def url():
        return redirect(url_for('hello_world'))
    

    render_template(模板渲染)

    from flask import render_template   # 模板渲染
    """模板放在templates文件夹内"""
    @app.route('/')
    def index():
        return render_template('index.html')
    
    

    SQLAlchemy(ORM数据库框架)

    配置文件:config.py

    # 数据库连接遵循这个语句
    # dialect+driver://username:password@host:port/database
    DIALECT = 'mysql'
    DRIVER = 'pymysql'
    USERNAME = 'root'
    PASSWORD = 'password'
    HOST = '127.0.0.1'
    PORT = '3306'
    DATABASE = 'DBname'
    
    SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(
        DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)
    
    SQLALCHEMY_TRACK_MODIFICATIONS = False      # 不提示警告
    

    主app文件:

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    import config
    
    app = Flask(__name__)      
    app.config.from_object(config)      #引入配置文件
    db = SQLAlchemy(app)                #实例化
    
    db.create_all()
    

    相关文章

      网友评论

          本文标题:python-Flask(模块)

          本文链接:https://www.haomeiwen.com/subject/rsgbcftx.html