Flask簡介html
Flask是一個基於Python開發而且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,而後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,若是要返回給用戶複雜的內容時,須要藉助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染後的字符串返回給用戶瀏覽器。
「微」(micro) 並不表示你須要把整個 Web 應用塞進單個 Python 文件(雖然確實能夠 ),也不意味着 Flask 在功能上有所欠缺。微框架中的「微」意味着 Flask 旨在保持核心簡單而易於擴展。Flask 不會替你作出太多決策——好比使用何種數據庫。而那些 Flask 所選擇的——好比使用何種模板引擎——則很容易替換。除此以外的一切都由可由你掌握。如此,Flask 能夠與您珠聯璧合。
默認狀況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫能夠勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 自己實現的同樣。衆多的擴展提供了數據庫集成、表單驗證、上傳處理、各類各樣的開放認證技術等功能。Flask 也許是「微小」的,但它已準備好在需求繁雜的生產環境中投入使用。
安裝python
pip install flask
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
一 基本使用mysql
from flask import Flask app = Flask(__name__) @app.route('/',methods=["GET","POST"])
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
二 配置文件jquery
flask中的配置文件是一個flask.config.Config對象(繼承字典),默認配置爲: { 'DEBUG': get_debug_flag(default=False), 是否開啓Debug模式 'TESTING': False, 是否開啓測試模式 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, } 方式一: app.config['DEBUG'] = True PS: 因爲Config對象本質上是字典,因此還可使用app.config.update(...) 方式二: app.config.from_pyfile("python文件名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") app.config.from_envvar("環境變量名稱") 環境變量的值爲python文件名稱名稱,內部調用from_pyfile方法 app.config.from_json("json文件名稱") JSON文件名稱,必須是json格式,由於內部會執行json.loads app.config.from_mapping({'DEBUG':True}) 字典格式 # 經常使用方式,可用繼承父類中配置或者重寫 app.config.from_object("python類或類的路徑") app.config.from_object('pro_flask.settings.TestingConfig') settings.py class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True PS: 從sys.path中已經存在路徑開始寫 PS: settings.py文件默認路徑要放在程序root_path目錄,若是instance_relative_config爲True,則就是instance_path目錄
三 路由系統正則表達式
經常使用路由系統有以上五種,全部的路由系統都是基於一下對應關係來處理:redis
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner @app.route('/index.html',methods=['GET','POST'],endpoint='index') @auth def index(): return 'Index' 或 def index(): return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) or app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) app.view_functions['index'] = index 或 def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner class IndexView(views.View): methods = ['GET'] decorators = [auth, ] def dispatch_request(self): print('Index') return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint 或 class IndexView(views.MethodView): methods = ['GET'] decorators = [auth, ] def get(self): return 'Index.GET' def post(self): return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
@app.route和app.add_url_rule參數: rule, URL規則 view_func, 視圖函數名稱 defaults=None, 默認值,當URL中無參數,函數須要參數時,使用defaults={'k':'v'}爲函數提供參數 endpoint=None, 名稱,用於反向生成URL,即: url_for('名稱') methods=None, 容許的請求方式,如:["GET","POST"] strict_slashes=None, 對URL最後的 / 符號是否嚴格要求, 如: @app.route('/index',strict_slashes=False), 訪問 http://www.xx.com/index/ 或 http://www.xx.com/index都可 @app.route('/index',strict_slashes=True) 僅訪問 http://www.xx.com/index redirect_to=None, 重定向到指定地址 如: @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 或 def func(adapter, nid): return "/home/888" @app.route('/index/<int:nid>', redirect_to=func) subdomain=None, 子域名訪問 from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'wupeiqi.com:5000' @app.route("/", subdomain="admin") def static_index(): """Flask supports static subdomains This is available at static.your-domain.tld""" return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>") def username_index(username): """Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == '__main__': app.run()
from flask import Flask, views, url_for from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) class RegexConverter(BaseConverter): """ 自定義URL匹配正則表達式 """ def __init__(self, map, regex): super(RegexConverter, self).__init__(map) self.regex = regex def to_python(self, value): """ 路由匹配時,匹配成功後傳遞給視圖函數中參數的值 :param value: :return: """ return value def to_url(self, value): """ 使用url_for反向生成URL時,傳遞的參數通過該方法處理,返回的值用於生成URL中的參數 :param value: :return: """ val = super(RegexConverter, self).to_url(value) return val # 添加到flask中 app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("\d+"):nid>') def index(nid): print(url_for('index', nid='888')) return 'Index' if __name__ == '__main__': app.run()
四 模版sql
一、模板的使用數據庫
在根目錄下建立文件夾templatesdjango
Flask使用的是Jinja2模板,因此其語法和Django無差異json
二、自定義模板方法
Flask中自定義模板方法的方式和Bottle類似,建立一個函數並經過參數的形式傳入render_template,如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h1>{{msg}}</h1> <h1>循環</h1> {% for i in lis %} 姓名{{i.name}} 年齡{{i.age}} {% endfor %} <h1>自定義函數</h1> {{ func('n1') }} </body> </html>
from flask import Flask,Response,redirect,render_template,request,Markup app = Flask(__name__) def func(x): print(x,"n1") #n1 return Markup('<input value="www.baidu.com">百度</input>') @app.route('/index/',methods=["GET"]) def index(): if request.method=="GET": return render_template('index.html',**{'msg':666,"lis":[{"name":"zhou","age":18}],'func':func}) if __name__ == '__main__': app.run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% macro input(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {{ input('n1') }} {% include 'tp.html' %} <h1>asdf{{ v.k1}}</h1> </body> </html>
注意:Markup等價django的mark_safe
在模版中引入靜態文件
<script src="{{ url_for('static',filename='jquery-3.3.1.min.js')}}"></script> app = Flask(__name__,template_folder="templates",static_folder="static/js",static_url_path="/static/js") # static_folder 是模版渲染時查找的靜態文件 static_url_path 是在瀏覽器訪問靜態文件地址
五 請求與響應
from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"]) def login(): # 請求相關信息 # request.method # request.args # request.form # request.values # request.cookies # request.headers # request.path # request.full_path # request.script_root # request.url # request.base_url # request.url_root # request.host_url # request.host # request.files # obj = request.files['the_file_name'] # obj.save('/var/www/uploads/' + secure_filename(f.filename)) # 響應相關信息 # return "字符串" # return render_template('html模板路徑',**{}) # return redirect('/index.html')
# return Response()
# return jsonify() 返回json數據
# response = make_response(render_template('index.html')) # response是flask.wrappers.Response類型 # response.delete_cookie('key') # response.set_cookie('key', 'value') # response.headers['X-Something'] = 'A value' # return response return "內容" if __name__ == '__main__': app.run()
六 Session
除請求對象以外,還有一個 session 對象。它容許你在不一樣請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,而且對 Cookies 進行密鑰簽名要使用會話,你須要設置一個密鑰。
- app.secret_key = "xxxxx"
設置:session['username'] = 'xxx'
在對session嵌套對內部作操做時,記得修改參數
session.modified = True
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) # set the secret key. keep this really secret: app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
自定義session
pip3 install Flask-Session run.py from flask import Flask from flask import session from pro_flask.utils.session import MySessionInterface app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.session_interface = MySessionInterface() @app.route('/login.html', methods=['GET', "POST"]) def login(): print(session) session['user1'] = 'alex' session['user2'] = 'alex' del session['user2'] return "內容" if __name__ == '__main__': app.run() session.py #!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): import redis self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序剛啓動時執行,須要返回一個session對象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在內存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序結束前執行,能夠保存session中全部的值 如: 保存到resit 寫入到用戶cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在內存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
第三方session
from flask import Flask,session from redis import Redis # RedisSessionInterface, \ # MemcachedSessionInterface, FileSystemSessionInterface, \ # MongoDBSessionInterface, SqlAlchemySessionInterface app = Flask(__name__) app.secret_key = 'suijksdfsd' # 方式一 from flask_session import RedisSessionInterface conn = Redis(host="0.0.0.0",port=6379) app.session_interface = RedisSessionInterface(conn,key_prefix='__',use_signer=False,permanent=True) # use_signer=False 不使用簽名加密 ,permanent若是是False關閉瀏覽器cookie就失效 # 方式二 from flask.ext.session import Session app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = Redis(host="0.0.0.0",port=6379) Session(app) @app.route('/login/') def login(): session['xxx'] = 123 return 'login' @app.route("/") def index(): print(session.get("xxx")) return "index" if __name__ == '__main__': app.run()
七 message(閃現)
from flask import Flask, flash, request, get_flashed_messages app = Flask(__name__) app.secret_key = 'some_secret' # 由於基於session,必需要設置該參數 @app.route('/') def index1(): messages = get_flashed_messages() # 一次性全取到,一個列表,只能取一次 print(messages) # ['zhoujunhao', 'www'] return "Index1" @app.route('/index/') def index3(): flash("zhoujunhao") return "ok3" @app.route('/set/') def index2(): v = request.args.get('p') flash("www") return 'ok2' if __name__ == "__main__": app.run()
八 請求擴展
a. before_request 請求以前作的事
a. 基於before_request作用戶登陸認證 @app.before_request def process_request(*args,**kwargs): if request.path == '/login': return None # 返回None表明經過,若是有返回值就不走視圖直接返回 user = session.get('user_info') if user: return None return redirect('/login')
b. after_request 返回時作的事
@app.after_request def process_response(response,*args,**kwargs): print("走了") return response # 返回什麼頁面顯示什麼
c. 執行順序 和django 1.7 1.8 1.9 同樣 process_request中若是有返回值,從最後一個process_response依次返回
from flask import Flask, render_template, request, redirect, session, url_for app = Flask(__name__) app.debug = True app.secret_key = 'siuljskdjfs' @app.before_request def process_request1(*args, **kwargs): print('process_request1 進來了') return "lanjie" @app.before_request def process_request2(*args, **kwargs): print('process_request2 進來了') @app.after_request def process_response1(response): print('process_response1 走了') return response @app.after_request def process_response2(response): print('process_response2 走了') return response @app.route('/index/', methods=['GET']) def index(): print('index函數') return "Index" if __name__ == '__main__': app.run() # process_request1 進來了 # process_response2 走了 # process_response1 走了
d. 錯誤頁面定製
@app.errorhandler(404) def error_404(arg): print(arg) # 錯誤信息 return "404錯誤了"
e. 模版中定製方法
@app.template_global() def sb(a1, a2): return a1 + a2 {{sb(1,2)}} @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3 {{ 1|db(2,3)}} # 把|前面的值當作第一個參數傳入
f. before_first_request 第一次請求時執行
@app.before_first_request # 只有第一次請求時執行 def first(*args,**kwargs): print("進來了") return None
九 中間件
class MyMiddleWare(object): def __init__(self,old_wsgi_app): self.old_wsgi_app = old_wsgi_app def __call__(self, environ, start_response): print("開始以前") ret = self.old_wsgi_app(environ, start_response) print("結束以後") return ret if __name__ == '__main__': # 把原來的app.wsgi_app當作參數傳入自定製的類,獲得一個對象賦值給app.wsgi_app, # 當調用app.wsgi_app時觸發Md的__call__方法,在內部又執行了原有的操做,可是在執行先後能夠添加一些操做 app.wsgi_app = MyMiddleWare(app.wsgi_app) app.run()
十 藍圖 blueprint
藍圖用於爲應用提供目錄劃分
小型應用:
大型應用程序:
其餘: 藍圖URL前綴:xxx = Blueprint('account', __name__,url_prefix='/xxx') 藍圖子域名:xxx = Blueprint('account', __name__,subdomain='admin') # 前提須要給配置SERVER_NAME: app.config['SERVER_NAME'] = 'wupeiqi.com:5000' # 訪問時:admin.wupeiqi.com:5000/login.html
十一 多App應用
from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from flask import Flask app1 = Flask('app01') app2 = Flask('app02') @app1.route('/index') def index(): return "app01" @app2.route('/index2') def index2(): return "app2" # http://www.oldboyedu.com/index # http://www.oldboyedu.com/sec/index2 dm = DispatcherMiddleware(app1, { '/sec': app2, }) if __name__ == "__main__": run_simple('localhost', 5000, dm)
源碼
class DispatcherMiddleware(object): """Allows one to mount middlewares or applications in a WSGI application. This is useful if you want to combine multiple WSGI applications:: app = DispatcherMiddleware(app, { '/app2': app2, '/app3': app3 }) """ def __init__(self, app, mounts=None): self.app = app self.mounts = mounts or {} def __call__(self, environ, start_response): script = environ.get('PATH_INFO', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('SCRIPT_NAME', '') environ['SCRIPT_NAME'] = original_script_name + script environ['PATH_INFO'] = path_info return app(environ, start_response) # 最終仍是調用了app的__call__()方法
Flask-SQLAlchemy
下載地址:https://pan.baidu.com/s/1Lu_Na2sCRM7Fc1JrZaQcMg
Flask-Script
安裝
pip install flask-script
使用
from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) app.config.from_object('settings.TestingConfig') @app.route('/') def hello_world(): return "index" @manager.command def func(args): """ 自定義命令 python manage.py[文件名] custom[函數名] 123[參數] """ print("執行func",args) #執行func 123 @manager.option("-n","--name",dest='name') @manager.option("-u","--url",dest='url') def foo(name,url): """ 關鍵字傳參 python 文件名 函數名 -n[--name]參數 -u[--url]參數 """ print(name,url) if __name__ == '__main__': # 命令行啓動項目:python manage.py[文件名] runserver manager.run()
Flask-migrate
安裝
pip install flask-migrate
使用
from flask import Flask from flask_script import Manager from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate,MigrateCommand db = SQLAlchemy() app = Flask(__name__) app.config.from_object("settings.DevelopmentConfig") manager = Manager(app) # 將db註冊到app中 db.init_app(app) migrate = Migrate(app,db) manager.add_command('db', MigrateCommand) """ # 數據庫遷移命名 python manage.py db init python manage.py db migrate python manage.py db upgrade """ @app.route('/') def hello_world(): return "index" @manager.command def func(args): """ 自定義命令 python manage.py[文件名] custom[函數名] 123[參數] """ print("執行func",args) #執行func 123 @manager.option("-n","--name",dest='name') @manager.option("-u","--url",dest='url') def foo(name,url): """ 關鍵字傳參 python 文件名 函數名 -n[--name]參數 -u[--url]參數 """ print(name,url) if __name__ == '__main__': # 命令行啓動項目:python manage.py[文件名] runserver manager.run()
class BaseConfig(object): # SESSION_TYPE = 'redis' # session類型爲redis # SESSION_KEY_PREFIX = 'session:' # 保存到session中的值的前綴 # SESSION_PERMANENT = True # 若是設置爲False,則關閉瀏覽器session就失效。 # SESSION_USE_SIGNER = False # 是否對發送到瀏覽器上 session:cookie值進行加密 SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:@0.0.0.0:3306/day146?charset=utf8" SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 30 SQLALCHEMY_POOL_RECYCLE = -1 # 追蹤對象的修改而且發送信號 SQLALCHEMY_TRACK_MODIFICATIONS = False
from script import db class Users(db.Model): """ 用戶表 """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) # email = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return '<User %r>' % self.username