直接上代码
# Import your dependencies
from flask import Flask, jsonify
# test_config=None, 因为这个程序没有在test environment
def create_app(test_config=None):
# Create and configure the app
# "name" basically just tells the application which directory it's host in
# if there's any additional configuration or relative paths it's looking for, it knows where to go.
# __name__ is the name of the current Python module
app = Flask(__name__)
# Define the first endpoint
# Using the app route decorator
# '/' 代表是本路径
@app.route('/')
def hello():
return jsonify({
'message': "Hello World"
})
# 如果是dict格式,必须得用jsonify to send an object containing the message
@app.route('/smile')
def smile():
# return jsonify({
# 'message': "Smile"
# })
return 'Smile' # return text
# Return the app instance
return app
运行这个程序
# 如果要判断folder name, 可以以哪个文件夹里有 __init__.py 文件
$ export FLASK_APP=<folder name>
$ export FLASK_ENV=development
# Make sure to run this command from the project directory
$ flask run
之后就看到
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Configured Application
Build larger applications that utilize multiple environments and configurations (production, development, testing, etc), this knowledge will be helpful for streamlining the development process.
- Import additional dependencies. You’ll need to import os in order to access the operating system and file structure import os.
- Set up your default configuration. When working in development your SECRET_KEY can be hardcoded as shown but for production should come from a secret environment variable. DATABASE is the path for the database file.
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
- If a config.py file is included in the instance folder, use its values to override the default configuration, for instance the SECRET_KEY. You can also enable a testing configuration if it was passed into the create_app function.
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
- Make the instance path directory. The app will create the database file within that directory so it needs to exist.
try:
os.makedirs(app.instance_path)
except OSError:
pass