【Web开发】Python实现Web服务器(Flask)

【Web开发】Python实现Web服务器(Flask),第1张

🍺Web服务器系列相关文章编写如下🍺:

  1. 🎈【Web开发】Node.js实现Web服务器(http模块)🎈
  2. 🎈【Web开发】Node.js实现Web服务器(express模块)🎈
  3. 🎈【Web开发】Python实现Web服务器(Flask)🎈

文章目录
  • 1、简介
  • 2、配置开发环境
    • 2.1 配置python
    • 2.2 配置VSCode
  • 3、官网示例测试
    • 3.1 代码示例1(最小的应用)
    • 3.2 代码示例2(修改ip和端口号)
    • 3.3 代码示例3(变量规则)
    • 3.4 代码示例4(URL构建)
    • 3.5 代码示例5(HTTP方法)
    • 3.6 代码示例6(会话)
    • 3.7 代码示例7(文件上传)
    • 3.8 代码示例8(返回json)
    • 3.9 代码示例9(返回图片)
  • 4、个人代码测试
    • 4.1 基于model-viewer的太阳系查看的网页
    • 4.2 基于openlayers的在线地图叠加geojson的网页
    • 4.3 基于leaflet的在线地图叠加mbtiles的网页
  • 5、扩展功能
    • 5.1 flask-admin
  • 结语

1、简介

https://flask.palletsprojects.com/en/2.1.x/
https://flask.net.cn/

Flask是一个用Python编写的Web应用程序框架。 它由 Armin Ronacher 开发,他领导一个名为Pocco的国际Python爱好者团队。 Flask基于Werkzeug WSGI工具包和Jinja2模板引擎。两者都是Pocco项目。

2、配置开发环境 2.1 配置python

安装virtualenv,并创建所需的虚拟环境。

pip install virtualenv


将在当前文件夹中创建新的虚拟环境:

mkdir myproject
cd myproject
virtualenv venv
venv\scripts\activate

注意:
(1)创建虚拟环境
如果使用venv,使用命令:$ python -m venv tutorial-env
如果使用virtualenv,则使用下面的命令:$ virtualenv snow-venv
如果你使用Python 3.3及以上版本,推荐使用标准库内置的venv 模块替代virtualenv。
如果你使用Python 2,就只能选择virtualenv,你需要额外安装它。pip install virtualenv

(2)激活虚拟环境
Windows(CMD.exe):$ tutorial-env\Scripts\activate.bat
Linux和macOS(bash/zsh):$ source tutorial-env/bin/activate

(3)退出虚拟环境:deactivate

通过键入 deactivate 来停用环境,您将返回正常的 shell。

deactivate

检测python虚拟环境安装是否成功。

import sys
# 输出python.exe路径
print(sys.executable)
# 输出lib路径
print(sys.prefix)


将在当前文件夹中安装flask库:

pip install flask

2.2 配置VSCode

把需要使用该环境的项目文件夹添加到工作区。
按下ctrl+,打开设置;
搜索框中搜索env,点击你的项目,在左边选扩展->python,如下图:

在Python:Venv Path一行添加你的虚拟环境文件夹,注意文件夹间以逗号分隔。

之后搜索python path,左边选扩展->python,下拉找到Python:Python Path,填入你的虚拟环境中的python解析器路径,如下图:

3、官网示例测试 3.1 代码示例1(最小的应用)

新建文件hello.py,输入如下内容:

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

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

执行之后,然后在VsCode的终端命令行输入如下命令:

set FLASK_APP=hellp.py
flask run

如果执行报错的话,可以试试如下代码:

$env:FLASK_APP="hello.py"
flask run

当然也可以将hello.py改成app.py的话,直接执行flask run也可以。

执行结果反馈如下:

网页访问结果如下:

3.2 代码示例2(修改ip和端口号)

新建文件hello2.py,输入如下内容:

  • hello2.py:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World,爱看书的小沐!'

if __name__ == '__main__':
   # app.run()
   app.run(host="127.0.0.1", port="8080")

执行结果如下:

浏览器访问结果如下:

3.3 代码示例3(变量规则)

新建文件hello3.py,输入如下内容:

  • hello3.py:
from flask import Flask, escape 
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World,爱看书的小沐!'

@app.route('/user/')
def show_user_profile(username):
    # show the user profile for that user
    return 'User: %s' % escape(username)

@app.route('/post/')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post: %d' % post_id

@app.route('/rev/')
def revision(revNo):
   return 'Revision Number: %f' % revNo

@app.route('/path/')
def show_subpath(path_name):
    # show the subpath after /path/
    return 'Path: %s' % escape(path_name)

if __name__ == '__main__':
   # app.run()
   app.run(host="127.0.0.1", port="8080")

浏览器访问结果如下:

3.4 代码示例4(URL构建)

新建文件hello4.py,输入如下内容:

  • hello4.py:
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/')
def index():
    return 'hello, index, 这是看书的小沐的首页!'

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

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest
   # return '{}\'s profile'.format(escape(guest))

@app.route('/user/')
def profile(username):
   if username =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest', guest = username))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', abc='/'))
    print(url_for('profile', username='爱看书的小沐'))

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

执行代码结果如下:

浏览器访问网址:http://127.0.0.1:5000/user/tomcat

浏览器访问网址:http://127.0.0.1:5000/user/admin

浏览器访问网址:http://127.0.0.1:5000

3.5 代码示例5(HTTP方法)

在myproject里新建子文件夹templates,用来存放flask的模板网页,这里新建一个测试网页hello5.html,内容如下:

<html>
   <body>
      <form action = "http://localhost:5000/login" method = "post">
         <p>Enter Name:p>
         <p><input type = "text" name = "message" />p>
         <p><input type = "submit" value = "submit" />p>
      form>
   body>
html>

新建文件hello5.py,输入如下内容:

  • hello5.py:
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('hello5.html')

@app.route('/success1/')
def get_success(name):
   return 'get: welcome %s' % name

@app.route('/success2/')
def post_success(name):
   return 'post: welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['message']
      return redirect(url_for('post_success',name = user))
   else:
      user = request.args.get('message')
      return redirect(url_for('get_success',name = user))

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

浏览器访问网址:http://127.0.0.1:5000

文本框输入“爱看书的小沐”,点击按钮submit之后,

3.6 代码示例6(会话)

有一种称为 session 的对象,允许你在不同请求 之间储存信息。这个对象相当于用密钥签名加密的 cookie ,即用户可以查看你的 cookie ,但是如果没有密钥就无法修改它。
使用会话之前你必须设置一个密钥,使用下面的命令生成随机数:

python -c 'import os; print(os.urandom(16))'
  • hello6.py:
from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'\xc0)\xb0\x97\x9f\xd8\x86\x83:\x19\x9fx\xb4h\xd4\x17'

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        

'''
@app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)

浏览器访问网址:http://127.0.0.1:5000/login

输入用户名之后,

或者:

  • hello6_2.py:
from flask import render_template
from flask import make_response
from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)
app.secret_key = 'fkdjsafjdkfdlkjfadskjfadskljdsfklj'

@app.route('/')
def index():
    if 'username' in session:
        username = session['username']
        return '登录用户名是:' + username + '
'
+ \ "点击这里注销" return "您暂未登录,
"
+ \ "点击这里登录" @app.route('/login', methods = ['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return '''

'''
@app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(debug = True)
3.7 代码示例7(文件上传)

在myproject里新建子文件夹templates,用来存放flask的模板网页,这里新建一个测试网页hello7.html,内容如下:

  • hello7.html:
<html>
<head>
  <title>File Uploadtitle>
head>
<body>
    <form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
        <input type="file" name="file"  />
        <input type="submit" value="提交" />
    form>
body>
html>
  • hello7.py:
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename

import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'upload/'

@app.route('/')
def index():
    return render_template('hello6.html')
    
@app.route('/upload')
def upload_file():
    return render_template('upload.html')

@app.route('/uploader',methods=['GET','POST'])
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        print(request.files)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))

        return 'file uploaded successfully'

    else:

        return render_template('upload.html')

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

浏览器访问网址:http://127.0.0.1:5000

选择一个文件beijing1.tif,点击按钮“提交”,

3.8 代码示例8(返回json)
  • hello8.py:
from flask import Flask, request, abort, make_response
import json

app = Flask(import_name=__name__)

@app.route('/')
@app.route('/login', methods=["GET","POST"])
def login():

    data = {
        "user_name": "爱看书的小沐",
        "user_age": 18,
        "city": "beijing",
    }

    res_json = json.dumps(data)
    #return res_json
    #return res_json, 200, {"Content-Type":"application/json"}
    #return jsonify(token=123456, gender=0)
    return jsonify(data)

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

浏览器访问结果如下:

3.9 代码示例9(返回图片)
  • hello9.py:
# encoding:utf8
from io import FileIO
from flask import Response, Flask

app = Flask(__name__)

@app.route("/image/")
def index(imageid):
    #image = FileIO("images/{}.png".format(imageid))
    with open("images/{}.png".format(imageid), 'rb') as f:
      image = f.read()
    resp = Response(image, mimetype="image/png")
    return resp

app.run(debug=True)

浏览器访问结果如下:

4、个人代码测试 4.1 基于model-viewer的太阳系查看的网页

该例子的具体介绍请见作者的另一篇文章,网址如下:
【小沐科普】小沐带您遨游太阳系(model-viewer,trimesh,Python)

这里通过编写python代码,搭建flask的web服务器环境,运行这个网页例子。

  • test_solarsystem.py:
#***************************************************************
#   Purpose:   基于model-viewer的太阳系查看的网页(Flask的web服务器)
#   Author:    爱看书的小沐
#   Date:      2022-5-8
#   Languages: python
#   Platform:  python 3.9 win64
#   OS:        Win10 win64
# **************************************************************

from flask import Flask, redirect, url_for, request, render_template, Response
from io import FileIO

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('solar_system.html')

@app.route("/images/")
def get_image(filename):
    with open("static/images/{}".format(filename), 'rb') as f:
      image = f.read()
    resp = Response(image, mimetype="image/jpg")
    return resp

@app.route("/glb/")
def get_binary(filename):
    data = FileIO("static/glb/{}".format(filename))
    resp = Response(data, mimetype="application/zip")
    return resp

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




4.2 基于openlayers的在线地图叠加geojson的网页

该例子的具体介绍请见作者的另一篇文章,网址如下:
【GIS开发】OpenLayers入门学习(JavaScript库)

  • test_openlayers.py:
#***************************************************************
#   Purpose:   基于openlayers的在线地图叠加geojson的网页(Flask的web服务器)
#   Author:    爱看书的小沐
#   Date:      2022-5-8
#   Languages: python
#   Platform:  python 3.9 win64
#   OS:        Win10 win64
# **************************************************************

from flask import Flask, redirect, url_for, request, render_template, Response
from io import FileIO

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('test_openlayers.html')

@app.route("/json/")
def get_binary(filename):
    data = FileIO("static/json/{}".format(filename))
    resp = Response(data, mimetype="application/json")
    return resp

if __name__ == '__main__':
   app.run(debug = True)
  • test_openlayers.html:
doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css" type="text/css">
    <style>
        .map {
            height: 45rem;
            width: 100%;
        }
    style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js">script>
    <title>OpenLayers exampletitle>
head>

<body>
    <h2>爱看书的小沐的地图h2>
    <div id="map" class="map">div>
    <script type="text/javascript">

        var pointGeoJsonLayer = new ol.layer.Vector({
            title: 'points',
            source: new ol.source.Vector({
                projection: 'EPSG:4326',
                url: 'json/china.json',
                format: new ol.format.GeoJSON()
            })
        });

        var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                }),
                pointGeoJsonLayer
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([104.1, 21.6]),
                zoom: 3
            })
        });
    script>
body>

html>

运行结果如下:

4.3 基于leaflet的在线地图叠加mbtiles的网页

该例子的具体介绍请见作者的另一篇文章,网址如下:
【GIS开发】Leaflet入门学习(Javascript库)

  • test_leaflet.py:
from flask import Flask, redirect, url_for, request, render_template, Response
from io import FileIO

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('test_leaflet.html')

@app.route("/json/")
def get_binary(filename):
    data = FileIO("static/json/{}".format(filename))
    resp = Response(data, mimetype="application/json")
    return resp

@app.route("/js/")
def get_js(filename):
    data = FileIO("static/js/{}".format(filename))
    resp = Response(data, mimetype="application/html")
    return resp

if __name__ == '__main__':
   app.run(debug = True)
  • test_leaflet.html:
DOCTYPE html>
<html>

<head>
    <title>Leaflet sampletitle>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin="" >script>

    >
    <script src="js/Leaflet.TileLayer.MBTiles.js">script>
    <script src="https://unpkg.com/sql.js@0.3.2/js/sql.js">script>
head>

<body>
    <div id="map" style="width: 900px; height: 380px">div>
    <script>
        var map = new L.Map('map').fitWorld();
 
        var mb = L.tileLayer.mbTiles('json/world_countries.mbtiles').addTo(map);
        mb.on('databaseloaded', function(ev) {
            console.info('MBTiles DB loaded', ev);
        });
        mb.on('databaseerror', function(ev) {
            console.info('MBTiles DB error', ev);
        });
    script>
body>

html>

运行结果如下:

5、扩展功能 5.1 flask-admin

https://flask-admin.readthedocs.io/

安装扩展flask-admin:

cd D:\test\myproject
virtualenv venv
venv\scripts\activate
pip install flask-admin

  • 测试代码1
from flask import Flask
from flask_admin import Admin

app = Flask(__name__)

# set optional bootswatch theme
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'

admin = Admin(app, name='microblog', template_mode='bootstrap3')
# Add administrative views here

app.run()

运行结果:

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进。o_O???
如果您需要相关功能的代码定制化开发,可以留言私聊作者。(✿◡‿◡)
感谢各位童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/874831.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存