Skip to content

Instantly share code, notes, and snippets.

@GunjiD
Last active July 8, 2021 11:48
Show Gist options
  • Save GunjiD/856639acf339d2d3fe7cf17344c363da to your computer and use it in GitHub Desktop.
Save GunjiD/856639acf339d2d3fe7cf17344c363da to your computer and use it in GitHub Desktop.

Flask Quickstart の翻訳

A Minimal Application 最小限のアプリケーション

A minimal Flask application looks something like this:
最小限の Flask アプリケーションはこのように見える:

from flask import Flask  

app = Flask(__name__)  

@app.route("/")  
def hello_world():  
    return "<p>Hello, World!</p>"  

So what did that code do?
このコードは何をしたか?

  1. First we imported the Flask class. An instance of this class will be our WSGI application.
    最初に私達は Flask クラスを import した。このクラスのインスタンスが私達の WSGI アプリケーションになる。

  2. Next we create an instance of this class. The first argument is the name of the application’s module or package. __name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.
    次にこのクラスのインスタンスを作成する。最初の引数はアプリケーションのモジュールまたはパッケージの名前である。 __name__ はこれに対する便利なショートカットであり、ほとんどの場合に適している。これは Flask がtemplates や静的ファイルなどのリソースをどこで探すかを知るために必要である。

  3. We then use the route() decorator to tell Flask what URL should trigger our function.
    次に route() decorator を使用してどの URL が関数をトリガーするかを Flask に指示する。

  4. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser.
    この関数はユーザーのブラウザに私達が表示したいメッセージを返す。デフォルトのコンテンツタイプは HTML なので、文字列中の HTML はブラウザでレンダリングされる。

Save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself.
hello.py などとして保存する。アプリケーションが flask.py を呼び出していないことを確認してください。なぜならこれは flask 自身とコンフリクトする可能性があるからである。

To run the application, use the flask command or python -m flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:
アプリケーションを実行するには、flask command または python -m flask を使う。実行する前に、FLASK_APP 環境変数をエクスポートして、アプリケーションが動作するようにターミナルに指示する必要がある。

$ export FLASK_APP=hello  
$ flask run  
 * Running on http://127.0.0.1:5000/  

Application Discovery Behavior アプリケーション検出動作

As a shortcut, if the file is named app.py or wsgi.py, you don’t have to set the FLASK_APP environment variable. See Command Line Interface for more details.
ショートカットとして、ファイルは app.py または wsgi.py という名前の場合、 FLASK_APP 環境変数を設定する必要がない。詳細について CLI を参照すること。

This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options.
これにより、とてもシンプルなビルトインサーバーが起動する。これはテストにとても良いが、おそらく本番環境で使用したいものではないだろう。 deployment オプションについては Deployment Options を参照すること。

Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.
http://127.0.0.1:5000/ を開くと、あなたの hello world グリーティングが表示されるはずである。

Externally Visible Server 外部から見えるサーバー

If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.
あなたがサーバーを実行すると、サーバーには自分のコンピューターからしかアクセスでき、ネットワークの他のコンピューターからはアクセスできないことがわかる。デバックモードではアプリケーションのユーザーがコンピューター上で任意の Python コードを実行することができるため、これがデフォルトである。

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:
あなたがデバッガーを無効にしている、またはネットワークのユーザーを信頼している場合、あなたはコマンドラインに --host=0.0.0.0 を追加するだけでサーバーを公開することができる。

$ flask run --host=0.0.0.0

This tells your operating system to listen on all public IPs.
これによりあなたの OS がすべての Public IP を listen するようになる。

What to do if the Server does not Start サーバーが起動しないときはどうすればよいか

In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.
python -m flask が失敗、または flask が存在しない場合、これが当てはまる理由は複数ある。まず最初に、あなたはすべてのエラーメッセージを確認する必要がある。

Old Version of Flask 古いバージョンの Flask

Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at Development Server to see the alternative method for running a server.
0.11 より古いバージョンの Flask には、アプリケーションを起動する様々な方法があった。要するに、 flask コマンド、または python -m flask も存在しなかった。その場合、2つのオプションがある: 新しい Flask のバージョンにアップグレードするか、開発サーバーを調べてサーバーを実行するための代替方法を確認する。

Invalid Import Name 無効な import 名

The FLASK_APP environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed.
FLASK_APP 環境変数は flask を実行時にインポートするモジュールの名前である。モジュールの名前が間違っている場合、起動時にインポートエラーが発生する(またはアプリケーションに移動するときにデバッグが有効になっている場合)。あなたに何をインポートしようとしたのか、なぜ失敗したのかを教える。

The most common reason is a typo or because you did not actually create an app object.
最も一般的な理由は、タイプまたは、実際にアプリを作成しなかったためである。

Debug Mode

The flask run command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.
flask 実行コマンドができることは、開発サーバーの実行だけではない。デバックモードを有効にすることで、コードが変更された場合にサーバーを自動的にリロードし、リクエスト中にエラーが発生した場合にブラウザにインタラクティブデバッガーを表示する。

Warning:

The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.
デバッガーはブラウザから任意の Python コードを実行することを許可している。ピンで保護されているが、以前として主要なセキュリティリスクを表している。本番環境で開発サーバーまたはデバッガーを実行しないようにすること。

To enable all development features, set the FLASK_ENV environment variable to development before calling flask run. すべての開発機能を有効にするには、 flask run を実行前に FLASK_ENV 環境変数を development に設定する。

$ export FLASK_ENV=development
$ flask run

See also: 以下も参照すること:

HTML Escaping

When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically.
HTML を返す場合(Flask のデフォルトの応答タイプ)、インジェクション攻撃を保護するために、出力にレンダリングされた user-provided の値をエスケープする必要がある。後で紹介する Jinja でレンダリングされた HTML テンプレートは、これを自動で行う。

escape(), shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you’re using untrusted data. ここに示される escape() は、手動で使用できる。簡潔にするためにほとんどの例では省略されているが、信頼できないデータをどのように使用しているかを常に認識する必要がある。

from markupsafe import escape

@app.route("/<name>")
def hello(name):
    return f"Hello, {escape(name)}!"

If a user managed to submit the name <script>alert("bad")</script>, escaping causes it to be rendered as text, rather than running the script in the user’s browser.
ユーザーが <script>alert("bad")</script> という名前を送信した場合、エスケープするとユーザーのブラウザでスクリプトを実行するのではなく、テキストとしてレンダリングされる。

in the route captures a value from the URL and passes it to the view function. These variable rules are explained below.
ルート内の <name> は URL から値を取得し、それをビュー関数に渡す。これらの可変ルールを以下に説明する。

Routing

Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.

Use the route() decorator to bind a function to a URL.

@app.route('/')
def index():
    return 'Index Page'

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

You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment