from flask import Flask app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>' @app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name if __name__ == '__main__': app.run(debug=True)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '
<h1>Hello World!</h1>
'
if __name__ == '__main__':
app.run(debug=True) (venv) $ python hello.py * Running on http://127.0.0.1:5000/ * Restarting with reloader
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '
<h1>Hello World!</h1>
'
@app.route('/user/<name>')
def user(name):
return '
<h1>Hello, %s!</h1>
' % name
if __name__ == '__main__':
app.run(debug=True) from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '
<p>Your browser is %s</p>
' % user_agent >>> from hello import app >>> from flask import current_app >>> current_app.name Traceback (most recent call last): ... RuntimeError: working outside of the application context >>> app_ctx = app.app_context() >>> app_ctx.push() >>> current_app.name 'hello' >>> app_ctx.pop()
(venv) % python >>> from hello import app >>> app.url_map Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>, <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>, <Rule '/user/<name>' (HEAD, OPTIONS, GET) -> user>])
@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400 from flask import make_response
@app.route('/')
def index():
response = make_response('
<h1>This document carries a cookie!</h1>
')
response.set_cookie('answer', '42')
return response from flask import redirect
@app.route('/')
def index():
return redirect('http://HdhCmsTestexample测试数据') from flask import abort
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '
<h1>Hello, %s</h1>
' % user.name from flask.ext.script import Manager manager = Manager(app) # ... if __name__ == '__main__': manager.run()
usage: hello.py [-h] {shell, runserver} ...
positional arguments:
{shell, runserver}
shell 在Flask应用程序上下文的内部运行一个Python Shell。
runserver 运行Flask开发服务器,例如:app.run()
optional arguments:
-h, --help 显示这个帮助信息并退出 (venv) $ python hello.py runserver --help
usage: hello.py runserver [-h] [-t HOST] [-p PORT] [--threaded]
[--processes PROCESSES] [--passthrough-errors] [-d]
[-r] optional arguments: -h, --help 显示这个帮助信息并退出 -t HOST, --host HOST -p PORT, --port PORT --threaded --processes PROCESSES --passthrough-errors -d, --no-debug -r, --no-reload
(venv) $ python hello.py runserver --host 0.0.0.0 * Running on http://0.0.0.0:5000/ * Restarting with reload
现在web服务器应该可以从网络中的任何一台计算机访问 http://a.b.c.d:5000 ,“a.b.c.d”是运行服务的计算机的外部IP地址。
更多用Python的Flask框架来搭建第一个Web应用相关文章请关注PHP中文网!
查看更多关于用Python的Flask框架来搭建第一个Web应用的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did82677