FlaskWeb开发-Part2-程序基本结构(第一个Flask Web程序)

FlaskWeb开发-Part2-程序基本结构(第一个Flask Web程序)

first.
首先,展示一个简单的示例:Flask默认在5000端口监听,执行以下hello.py程序,可以通过浏览器访问:http://127.0.0.1:5000/
显示为hello,world

#hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hello, World!</h1>'
if __name__ == '__main__':
    app.run(debug=True)

浏览器显示:
在这里插入图片描述

其中有三点需要注意:
1.重启电脑,或者terminal之后,进入文件夹之后,要打开venv

source venv/bin/activate

2.使用书籍上:git

git checkout 2a

得到2a这个版本后,需要修改文件读写权限:

sudo chmod 777 ./hello.py
//add the following code at the tail
if __name__ == '__main__':
    app.run(debug=True)

3.使用命令:

python hello.py

之后访问浏览器才可以。
接下来还有几个展示程序,其中return redirect()可以跳转到对应网址,实验中为百度。zzytest为我自己添加的函数:

from flask import Flask
from flask import make_response
from flask import redirect
from flask import abort
from flask import request

app = Flask(__name__)


@app.route('/')
def index():
    #return '<h1>hello world</h1>'
    #return '<h1>Bad request</h1>',400
    '''# this is a make_response test
    response = make_response('<h1>this document carries a cookie!</h1>')
    response.set_cookie('answer','42')
    return response
    '''
    #return redirect('http://www.baidu.com')
    user_agent = request.headers.get('User-Agent')
    return '<p>Your brower is %s</p>' % user_agent

@app.route('/user/<id>')
def get_user(id):
    user = load_user(id)
    if not user:
        abort(404)
    return '<h1>hello,%s</h1>' % user.name
    
@app.route('/user/<name>')
def user(name):
    return '<h1>Hello, {}!</h1>'.format(name)

@app.route('/zzytest/')
def zzytest():
    return '<h1>this is zzy test!</h1>'

if __name__ == '__main__':
    app.run(debug=True)

在这里插入图片描述
突然发现图片违规了,其实就是一个“百度搜索”的界面。
其实,就是建立一个对应关系:将要访问的目录和对应函数映射起来

@app.route('/')
def index():
    return '<h1>Hello, world</h1>'

second.
使用Flask扩展:使用Flask-Script支持命令行选项
安装:

pip install flask-script

可以选择shell, runserver运行

from flask import Flask
app = Flask(__name__)

from flask_script import Manager
manager = Manager(app)

@app.route('/')
def index():
    return '<h1>hello world!</h1>'

if __name__ == '__main__':
    manager.run()

可以选择网络接口:

python hello.py runserver --host 0.0.0.0

另一种可以运行hello world的代码:

from werkzeug.wrappers import Request,Response
from werkzeug.serving import run_simple


@Request.application
def hello(request):
    return Response('Hello World')

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    run_simple('localhost',4000,hello)

运行示意图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值