Flask入門

什麼是Flask?

用於搭建Web應用的微框架。說其「微」,是指其核心足夠簡單,可擴展,與Django的理念相反。html

(web development, one drop at a time  vs  the web framwork for perfectionists with deadlines)python

只要建立好app,作好路由映射(基於裝飾器),立刻就能夠讓Flask運轉起來web

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

 

訪問本機的5000端口,就能看到結果。flask

功能初探

可定義多映射cookie

@app.route('/index')
@app.route('/')
def index():
    return 「home page「

可定義訪問方法,參數和參數類型,app

@app.route('/profile/<int:uid>', methods=['GET', 'POST'])
def profile(uid):
    return "profile", str(uid)

得到請求信息,定義響應信息框架

from flask import make_response, request

@app.route('/request')
def request_demo():
    res = ''
    key = request.args.get('demo_key', 'default_value')
    res = res + request.url + '++' + request.path + '<br>'
    for property in dir(request):
        res = res + str(property) + '|==|<br>' + str(eval('request.' + property)) + '<br>'
    response = make_response(res)
    response.set_cookie('cookie_key', key)
    response.status = '404'
    response.headers['header_key'] = 'header_value'
    return response

重定向和處理錯誤ui

from flask import redirect

@app.route('/redirect_target')
def redirected():
    return 'target'


@app.route('/from_here')
def redirect_demo(code):
    return redirect('/redirect-target')


@app.errorhandler(404)
def page_not_found(error):
    return render_template('not_found.html')

在先後請求以前傳遞信息,有消息閃現(Message Flashing)機制url

from flask import flash, get_flashed_messages

@app.route('/login')
def login():
    # 每登陸一次都爲把消息壓入消息隊列中,首頁的提示信息會一直增長
    flash('登陸成功')
    return 'ok'


@app.route('/')
def index():
    res = ''
    for msg in get_flashed_messages():
        res = res + msg + '<br>'
    return res

Jinja2模板spa

{% extends "base.html" %}

<title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>

可安裝flask_script模塊爲Flask編寫外部腳本,方便進行調試和管理

from flask_script import Manager
from demo import app

manager = Manager(app)


@manager.command
def hello(name):
    print('hello', name)


@manager.command
def initialize_database():
    """initialize database"""
    print('database started.')


if __name__ == '__main__':
  # 默認有runserver命令,啓動server manager.run()
python manage.py hello demo
python manage.py initialize_database
python manage.py runserver

ORM

from flask_ins import db


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(32))
    # 頭像
    head_url = db.Column(db.String(236))
    # 用戶能夠有多張圖片,一對多
    images = db.relationship('Image', backref='user', lazy='dynamic')

    def __init__(self, username, password):
        self.username = username
        self.password = password
        # 調用unsplash的接口,生成隨即圖片
        self.head_url = get_image_url(icon_url)

    def __repr__(self):
        return '<User %d %s>' % (self.id, self.username)


class Image(db.Model):
    __tablename__ = 'image'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 外鍵,與relationship搭配使用
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    url = db.Column(db.String(512))
    created_date = db.Column(db.DateTime)

    def __init__(self, url, user_id):
        self.url = url
        self.user_id = user_id
        self.created_date = datetime.now()

    def __repr__(self):
        return'<Image %d %s>' % (self.id, self.url)

 

 

參考資料:

http://flask.pocoo.org/docs/1.0/

http://jinja.pocoo.org/docs/2.10/

https://flask-script.readthedocs.io/en/latest/

相關文章
相關標籤/搜索