Virtual environment installation instructions and Flask view, advanced view, blueprint, subdomain

1. Virtual environment installation

In general, after python is installed, it exists in the global environment. If the project needs it, you need to equip the project with its own python environment, so this environment is a virtual environment. The virtual environment configuration is as follows

#1、pipenv安装
pip install pipenv
#2、在E盘创建一个目录,将新建的系统环境变量WORKON_HOME指向创建的目录
#3、dos切向E盘中创建的目录,进行虚拟环境安装(第一次为安装,后续为进入虚拟环境)
pipenv shell
#4、虚拟环境搭建完成后,会自动进入虚拟环境
#5、退出虚拟环境
exit
#6、删除整个环境
pipenv --rm

Note: After the virtual environment is created in the third step, the Pipfile file appears in the directory folder created in the E disk

[[source]]
name = "pypi"
url = "https://pypi.org/simple"  //指定国内pip源,不然pip其他包的时候很慢
verify_ssl = true
[dev-packages]			//开发环境
[packages]			//生产环境
[requires]			//python版本
python_version = "3.6"

Two, Flask

# 从flask框架中导入Flask类
from flask import Flask

# 传入__name__初始化一个Flask实例
app = Flask(__name__)


# app.route装饰器映射URL和执行的函数。这个设置将根URL映射到了hello_world函数上
@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    # 运行本项目,host=0.0.0.0可以让其他电脑也能访问到该网站,port指定访问的端口。默认的host是127.0.0.1,port为5000。可以开启debug模式
    app.run(host='0.0.0.0', port=9000, debug=True)

2.1 URL and view

2.1.1 The parameter passing type can be defined in route
from flask import Flask

app = Flask(__name__)

@app.route('/<aid>/')
def index(aid):
	return f'这是第{aid}个'

You can add restrictions to the above

  • string: Default.
  • int: Plastic surgery. <int:aid>
  • float: floating point type. <float:aid>
  • path: similar to string. But the slash <path:aid> can be passed in the url
  • uuid: never re-encode, often used for ID
  • any: You can specify multiple <any(article,blog):aid>
2.1.2 HTTP request mode can be specified in route

get request
Insert picture description here
post request
Insert picture description here

2.1.3 url_for and redirection

The benefits of the url_for method are as follows:
1. Optimize the jump, the address modification in the route does not affect the jump, as long as the target method does not change
2. The url_for() function will escape some special characters and unicode strings. These things will Automatically do it for us

from flask import Flask, url_for, redirect

app = Flask(__name__)

@app.route('/login/<aid>/')
def login(aid):
	return f'login{aid}'


@app.route('/name_load/')
def name_load():
	return redirect(url_for("login",aid=2))
2.1.4 Response

The return Response is similar to the return string.
There are several

@app.route('/')
def s_root():
    #return '第一个页面'
    #return Response('first page')
    #设置状态码
    #return Response(response=TUP[0],status=666)
    #返回元组形式
    #return  TUP[0],404
    #使用make_response,此函数还能夹杂cookie,header
    return make_response(TUP[0])

2.2 View advanced

2.2.1 Standard class attempts

Inherit views.View, override the dispatch_request method, and feed back the content to the display in the method.

from flask import Flask
from flask.views import View
#创建一个Flask对象
app = Flask(__name__)

#创建一个视图类
class DemoView(View):
	#dispatch_request此方法必须重写,否则丢出raise异常
	def dispatch_request(self):
		return '标准类视图'
#定义规则
app.add_url_rule('/',view_funv=DemoView('ViewDemo'))


if __name__ == '__main__':
	app.run(debug=True, port=8000)
2.2.2 View based on HTTP method

Inherit the views.MethodView class to compile methods such as get and post
@app.route('/',methods['GET','POST']) advanced version

from flask import Flask, render_template, request
from flask.views import MethodView
#创建Flask对象
app = Flask(__name__)
#创建一个类,继承MethodView
class GetPostDemo(MethodView):
	#get方法
	def get(self):
		return render_template('login.html')
	#post方法,将接收到的数据进行比对
	def post(self):
		name = request.form.get('name')
		password=request.form.get('password')
		if name == 'kml' and password == '123':
			return self.SuccessDemo()
		else:
			return self.get()
	#post中接收内容,若错误,跳转至FormDemo.html
	def SuccessDemo(self):
		return render_template('FormDemo.html')

app.add_url_rule('/',view_func=GetPostDemo.as_view('GetPost'))


if __name__ == '__mian__':
	app.run(debug=True, port=8001)

2.3 Blueprint

The blueprint can rationalize the structure, facilitate the division of labor and subsequent maintenance

Insert picture description here
As shown in the figure above, the instructions are as follows:
1. Create a blueprint folder
2. Blueprintmain.py is the main view view; blueprintDemo.py is the blueprint view

Blueprint description

from flask import Blueprint, render_template
from flask.views import View
#创建Blueprint对象
#第一个参数:name
#第二个参数:import name
#template_folder,此函数设定表示。当主templates中文件不存在时,将在蓝图中的templates文件夹中寻找
#url_prefix='/admin',此设定表示,若需要浏览蓝图中的视图,网址为xxx/admin/蓝图中的路由定义
bp = Blueprint('blueprintdemo', __name__, template_folder='templates')

#定义demo类,继承View类
class demo(View):
	#需重写dispatch_request
	def dispatch_request(self):
		return render_tempalate('blueprint_demo.html')

#定义路由
bp.add_url_rule('/', view_func=demo.as_view('demo'))

Main view description

from flask import Flask
from blueprint import blueprintDemo
#创建Flask对象
app = Flask(__name__)
#将蓝图注册到主视图
app.register_blueprint(blueprintDemo.bp)

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

2.4 Subdomain

Subdomains are generally implemented through blueprints. SERVER_NAME needs to be configured in the main view. The Blueprint of the blueprint adds the parameter subdomain, which represents the subdomain name. Host configuration again

Blueprint description

from flask import Blueprint, render_template
from flask.views import View

bp = Blueprint('blueprintdemo', __name__, template_folder='templates', subdomain='kk')

@bp.route('/')
def index():
	return render_template('blueprint_demo.html')

Main view description

from flask import Flask
from blueprint import blueprintDemo


app = Flask(__name__)
#配置服务启动名称
app.config['SERVER_NAME'] = 'keminglang.com:10000'
app.register_blueprint(blueprintDemo.bp)


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

hosts file to configure DNS

127.0.0.1 keminglang.com:10000
127.0.0.1 kk.keminglang.com:10000

Guess you like

Origin blog.csdn.net/qq_37697566/article/details/105386486