!!!Flask [Python][Angular] {{amazon B00XZTYMG6}} *http://flask.pocoo.org/ !!!インストール *http://flask.pocoo.org/docs/0.12/installation/ *Windows , python3 > pythoh -m venv flask > cd flask\Scripts > activate (flask)> pip install Flask !!Visual Studio Code {{ref_image flask_vscode_settings.jpg}} // 既定の設定とユーザー設定を上書きするには、このファイル内に設定を挿入します { "python.pythonPath": "C:\\workspaces\\venv\\flask\\Scripts\\python", "python.autoComplete.extraPaths": [ "C:\\workspaces\\venv\\flask\\Lib\\site-packages" ], "python.linting.enabled": false, } !!Git *Github にリポジトリ作成 **https://github.com/pppiroto/flask_sample.git ::ローカルリポジトリを初期化 > git init ::ローカルリポジトリにコミット > git add . > git commit -m "flask lesson init" > git branch * master ::リモートリポジトリの設定 > git remote add origin https://github.com/pppiroto/flask_sample.git ::リモートリポジトリにpush > git push origin master !!!クイックスタート *http://flask.pocoo.org/docs/0.12/quickstart/ !!/hello.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello world!" !!サーバー起動 *Visual Studio Code、Powershell (flask) PS C:\workspaces\vscode\flask_sample> set-item env:FLASK_APP hello.py (flask) PS C:\workspaces\vscode\flask_sample> python -m flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) {{ref_image flask_run_server.jpg}} !デバッグモード PS> set-item env:FLASK_DEBUG 1 !!ルーティング from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello_world(): return 'Hello world!' !!変数 @app.route('/user//') def show_user_profile(username, age): return 'User {0} {1}'.format(username,age) ::<コンバーター:変数> ,コンバーター,説明 ,string,'/'以外のすべてのテキスト(デフォルト) ,int,整数 ,float,浮動小数点数 ,path,'/'を受け付ける ,any,与えられるアイテムの一つに一致 ,uuid,UUID文字列 !!ユニークURL / リダイレクトの振る舞い *FlaskのURLルールは、[Werkzeug|http://werkzeug.pocoo.org/]のルーティングモジュールに基づく *このモジュールの背後にあるアイディアは、Apacheなど過去のHTTPサーバーの先例にもとづいた、美しくユニークなURLをを保証すること。 @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' *これらは同じように見えるが、末尾の/の扱いが異なる。 *projectsエンドポイントのための正統なURLは末尾に/を伴う。ファイルシステムのフォルダと同様 *末尾の/がない状態で、アクセスした場合、Flaskは末尾に/がある正統なURLにリダイレクトする *末尾の/ない例は、ファイルシステムのファイルと同様、末尾に/を伴ってアクセスされた場合、404 Not Foundエラーとなる !!URL 生成 *url_for()関数は、関数名を最初の、関数の引数を以降の引数としてとり、URLを生成する from flask import Flask,url_for app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello_world(): return 'Hello world!' @app.route('/user//') def show_user_profile(username, age): return 'User {0} {1}'.format(username,age) @app.route('/urls') def print_urls(): return '''
  1. index() = {0}
  2. hello_world() = {1}
  3. show_user_profile('piroto',46) = {2}
'''.format( url_for('index'), url_for('hello_world'), url_for('show_user_profile',username='piroto',age=46)) {{ref_image flask_url_for.jpg}} !!HTTP メソッド * from flask import request @app.route('/method_check', methods=['GET','POST','HEAD']) def method_check(): if request.method == 'GET': return "HTTP METHOD GET" return "HTTP METHOD {0}".format(request.method) !!静的ファイル @app.route('/static_path') def print_static_file_url(): return url_for('static', filename='style.css') {{ref_image flask_static.jpg}} !!テンプレート *Flaskでは、[Jinja2|http://jinja.pocoo.org/]テンプレートエンジンが自動で設定される *アプリケーションがモジュールか、パッケージ化によって、以下の構成のtempletesフォルダに配置する ::モジュール /アプリケーション.py /templates /テンプレート.html ::パッケージ /アプリケーション /__init__.py /templates /テンプレート.html ::テンプレート利用 from flask import Flask, render_template @app.route('/render_sample/') def render_sample(param=None): return render_template('render_sample.html',param=param) ::テンプレート Rendering Sample {% if param %}

Parameter : {{ param }}!

{% else %}

No parameter found.

{% endif %} {{ref_image flask_template.jpg}} *テンプレートでは、request、session、および g オブジェクトにアクセスできる *g オブジェクトは、必要に応じて情報を格納できる *テンプレートは特に[継承|]http://flask.pocoo.org/docs/0.12/patterns/templateinheritance/#template-inheritanceされる場合有用 *基本的にテンプレートは各ページにヘッダーやナビゲーションなどを確実に表示する !自動エスケープ *自動エスケープは有効 *安全と確信できる場合、Markupクラスもしくは、 |safeフィルターを使用する ::テンプレート Safe Rendering Sample

{{ param1 }}

{{ param2 }}

{{ param3 | safe}}

:: from flask import Markup @app.route('/render_safe_var') def render_safe_var(param=None): return render_template('render_safe_var.html', param1="

Sub title

", param2=Markup("

Mark up Sub title

"), param3="

Safe filtered Sub title

") {{ref_image flask_safe_var.jpg.jpg}} !!リクエストデータへのアクセス *クライアントが送信したリクエストデータは、request グローバルオブジェクトにより提供される *context locals により、グローバルオブジェクトをどうやってスレッドセーフにし管理している !Context Locals *Flaskのグローバルオブジェクトは実際には特定コンテキストローカルオブジェクトのプロキシ !!!Tips !!Session *http://flask.pocoo.org/docs/0.12/quickstart/#sessions from flask import Flask, session app = Flask(__name__, static_folder='app') app.secret_key = "hoge" def use_session: sessio["foo"] = "bar" !!CRSF *http://flask.pocoo.org/snippets/3/ *[Angular + HttpClientXsrfModule + Flask で CSRF|http://typea.info/blg/glob/2018/01/angular-httpclientxsrfmodule-flask-csrf.html] !!Cookie *http://flask.pocoo.org/snippets/30/ *https://stackoverflow.com/questions/37068604/flask-sessions-where-are-the-cookies-stored !!テンプレート !ディレクトリを変える *http://d.hatena.ne.jp/aroma_black/20101108/1289226596