Python Language                
            フラスコ
        
        
            
    サーチ…
前書き
Flaskは、Pintrest、Twilio、Linkedinなどの主要なWebサイトを実行するために使用されるPythonマイクロウェブフレームワークです。このトピックでは、フロントエンドとバックエンドの両方のWeb開発でFlaskが提供するさまざまな機能について説明します。
構文
- @ app.route( "/ urlpath"、methods = ["GET"、 "POST"、 "DELETE"、 "PUTS"、 "HEAD"、 "OPTIONS"])
- @app.route( "/ urlpath / <param>"、メソッド= ["GET"、 "POST"、 "DELETE"、 "PUTS"、 "HEAD"、 "OPTIONS"])
基礎
次の例は、基本的なサーバーの例です。
# Imports the Flask class
from flask import Flask
# Creates an app and checks if its the main or imported
app = Flask(__name__)
# Specifies what URL triggers hello_world()
@app.route('/')
# The function run on the index route
def hello_world():
    # Returns the text to be displayed
    return "Hello World!"
# If this script isn't an import
if __name__ == "__main__":
    # Run the app until stopped
    app.run()
このスクリプトを実行すると(すべての依存関係がインストールされた状態で)、ローカルサーバーが起動されます。ホストは、通常localhostと呼ばれる127.0.0.1です。このサーバーは、デフォルトでポート5000で実行されます。 Webサーバーにアクセスするには、Webブラウザーを開き、URL localhost:5000または127.0.0.1:5000 (差なし)を入力します。現在、あなたのコンピュータだけがウェブサーバにアクセスできます。 
 app.run()は、 host 、 port 、およびdebugの 3つのパラメータがあります。ホストはデフォルトで127.0.0.1ですが、これを0.0.0.0設定すると、URL上のプライベートIPアドレスを使用してネットワーク上のどのデバイスからでもWebサーバーにアクセスできます。ポートはデフォルトで5000ですが、パラメータがポート80に設定されている場合、ブラウザはデフォルトでポート80を使用するため、ポート番号を指定する必要はありません。デバッグオプションに関しては、開発プロセス中(生産中ではない)にFlaskプロジェクトに変更が加えられたときにサーバーが再起動するので、このパラメータをTrueに設定すると役立ちます。 
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80, debug=True)
ルーティングURL
 Flaskでは、URLルーティングは伝統的にデコレータを使用して行われます。これらのデコレータは静的ルーティングやパラメータ付きURLのルーティングに使用できます。次の例では、このFlaskスクリプトがWebサイトwww.example.com実行しているとします。 
@app.route("/")
def index():
    return "You went to www.example.com"
@app.route("/about")
def about():
    return "You went to www.example.com/about"
@app.route("/users/guido-van-rossum")
    return "You went to www.example.com/guido-van-rossum"
その最後のルートでは、/ users /とプロファイル名を持つURLを指定すると、プロファイルを返すことができます。 Flaskは、すべてのユーザーに@app.route()を含めるのはひどく非効率的で面倒なので、URLからパラメータを取るようにしています: 
@app.route("/users/<username>")
def profile(username):
    return "Welcome to the profile of " + username
cities = ["OMAHA", "MELBOURNE", "NEPAL", "STUTTGART", "LIMA", "CAIRO", "SHANGHAI"]
@app.route("/stores/locations/<city>")
def storefronts(city):
    if city in cities:
        return "Yes! We are located in " + city
    else:
        return "No. We are not located in " + city
HTTPメソッド
2つの最も一般的なHTTPメソッドは、 GETとPOSTです。 Flaskは、使用されるHTTPメソッドに応じて、同じURLから異なるコードを実行できます。たとえば、アカウントを持つWebサービスでは、サインインページとサインインプロセスを同じURLでルーティングするのが最も便利です。ブラウザでURLを開いたときと同じGETリクエストはログインフォームを表示し、POSTリクエスト(ログインデータを含む)は別々に処理する必要があります。 DELETEおよびPUT HTTPメソッドを処理するためのルートも作成されます。
@app.route("/login", methods=["GET"])
def login_form():
    return "This is the login form"
@app.route("/login", methods=["POST"])
def login_auth():
    return "Processing your data"
@app.route("/login", methods=["DELETE", "PUT"])
def deny():
    return "This method is not allowed"
コードを単純化するために、フラスコからrequestパッケージをインポートすることができます。 
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
    if request.method == "DELETE" or request.method == "PUT":
        return "This method is not allowed"
    elif request.method == "GET":
        return "This is the login forum"
    elif request.method == "POST":
        return "Processing your data"
 POSTリクエストからデータを取得するには、 requestパッケージを使用する必要があります。 
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
    if request.method == "DELETE" or request.method == "PUT":
        return "This method is not allowed"
    elif request.method == "GET":
        return "This is the login forum"
    elif request.method == "POST":
        return "Username was " + request.form["username"] + " and password was " + request.form["password"]
ファイルとテンプレート
 return文にHTMLマークアップを入力する代わりに、 render_template()関数を使用することができます: 
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/about")
def about():
    return render_template("about-us.html")
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80, debug=True)
これは、テンプレートファイルabout-us.htmlを使用します。アプリケーションでこのファイルが見つかるように、ディレクトリを次の形式で整理する必要があります。 
- application.py
/templates
    - about-us.html
    - login-form.html
/static
    /styles
        - about-style.css
        - login-style.css
    /scripts
        - about-script.js
        - login-script.js
最も重要なことは、HTML内のこれらのファイルへの参照は次のようになります。
 <link rel="stylesheet" type="text/css", href="{{url_for('static', filename='styles/about-style.css')}}"> 
静的フォルダの下のstylesフォルダにあるabout-style.cssを探すようアプリケーションにabout-style.cssします。パスの同じフォーマットは、イメージ、スタイル、スクリプト、またはファイルへのすべての参照に適用されます。 
Jinjaテンプレート
Meteor.jsと同様に、Flaskはフロントエンドのテンプレートサービスと統合されています。フラスコは、デフォルトでJinjaテンプレートを使用します。テンプレートを使用すると、HTMLファイルで条件やループなどの小さなスニペットを使用できます。
テンプレートをレンダリングすると、テンプレートファイル名を超えるパラメータがHTMLテンプレートサービスに渡されます。次のルートでは、ユーザー名と日付を(他の場所の関数から)HTMLに渡します。
@app.route("/users/<username>)
def profile(username):
    joinedDate = get_joined_date(username) # This function's code is irrelevant
    awards = get_awards(username) # This function's code is irrelevant
    # The joinDate is a string and awards is an array of strings
    return render_template("profile.html", username=username, joinDate=joinDate, awards=awards)
このテンプレートがレンダリングされると、 render_template()関数から渡された変数を使用できます。 profile.htmlの内容はprofile.htmlです。 
<!DOCTYPE html>
<html>
    <head>
        # if username
            <title>Profile of {{ username }}</title>
        # else
            <title>No User Found</title>
        # endif
    <head>
    <body>
        {% if username %}
            <h1>{{ username }} joined on the date {{ date }}</h1>
            {% if len(awards) > 0 %}
                <h3>{{ username }} has the following awards:</h3>
                <ul>
                {% for award in awards %}
                    <li>{{award}}</li>
                {% endfor %}
                </ul>
            {% else %}
                <h3>{{ username }} has no awards</h3>
            {% endif %}
        {% else %}
            <h1>No user was found under that username</h1>
        {% endif %}
        {# This is a comment and doesn't affect the output #}
    </body>
</html>
異なる解釈のために、次の区切り文字が使用されます。
-  {% ... %}はステートメントを表し{% ... %}
-  {{ ... }}はテンプレートが出力される式を示す
-  {# ... #}はコメントを表し{# ... #}(テンプレート出力には含まれません)
-  {# ... ##は、残りの行が文として解釈されるべきであることを意味します
要求オブジェクト
 requestオブジェクトは、ルートに対して行われたリクエストに関する情報を提供します。このオブジェクトを使用するには、フラスコモジュールからインポートする必要があります。 
from flask import request
URLパラメータ
前の例ではrequest.methodとrequest.formが使用されていましたが、 request.argsプロパティを使用してURLパラメータのキー/値のディクショナリを取得することもできます。 
@app.route("/api/users/<username>")
def user_api(username):
    try:
        token = request.args.get("key")
        if key == "pA55w0Rd":
            if isUser(username): # The code of this method is irrelevant
                joined = joinDate(username) # The code of this method is irrelevant
                return "User " + username + " joined on " + joined
            else:
                return "User not found"
        else:
            return "Incorrect key"
    # If there is no key parameter
    except KeyError:
        return "No key provided"
このコンテキストで正しく認証するには、次のURLが必要になります(ユーザー名をユーザー名に置き換えてください:
 www.example.com/api/users/guido-van-rossum?key=pa55w0Rd 
ファイルのアップロード
 POSTリクエストで提出されたフォームにファイルアップロードが含まれていた場合、ファイルはrequestオブジェクトを使用して処理できます。 
@app.route("/upload", methods=["POST"])
def upload_file():
    f = request.files["wordlist-upload"]
    f.save("/var/www/uploads/" + f.filename) # Store with the original filename
クッキー
要求は、URLパラメータに類似した辞書内のクッキーを含むこともできる。
@app.route("/home")
def home():
    try:
        username = request.cookies.get("username")
        return "Your stored username is " + username
    except KeyError:
        return "No username cookies was found")