


Detailed explanation of Web framework (Flask) in python (code example)
flask
flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务。
Using flask
When you write a function, if you want everyone to use it, you need to use flask to achieve this goal.
Import falsk.Flask class
Instantiate a Flask object
Bind routing
Run flask application
# 1. 导入Flask类; from flask import Flask # 2. 实例化一个Flask对象; # __name__是模块的名称或者包的名称 # 作用: 根据这个参数确定flask应用的路径, 从而快速查找模板和html文件的默认路径; # 模块就是python文件; 包就是目录(跟普通目录多加一个__init__.py); # app = Flask(__name__) # 3-1.基本路由:通过路由绑定一个视图函数 # @app.route('/'): 告诉Flask哪个URL才能出发对应的函数, 又称为路由; # 对应定义了一个视图函数, 也就是返回给用户浏览器显示的内容; @app.route('/') def index(): return "<h1 id="hello-world">hello world</h1>" @app.route('/login/') def login(): return "login" # 4. 运行Flask应用, 可以指定ip和端口; # '0.0.0.0' 所有的IP都可以访问到; app.run('0.0.0.0', 9000)
##Routing and variable rulesIn the flask framework, routing Represents the URL requested by the user and finds its corresponding processing function
Rules for common routing
- Part of the URL can be marked as a variable
- Common types of variables in routing in flask:
int, string, float, path, uuid
from flask import Flask, request app = Flask(__name__) @app.route('/<id>/comments/') def comment1(id): return "Comment id: %s" %(id) @app.route('/welcome/<user>/') def welcome(user): app.logger.debug('this is a debug') app.logger.warning('this is a warn') return user + "用户,欢迎来到SheenStar的主页" # 特殊的url地址: http://www.baidu.com/query?id=13&name=clotho @app.route('/query') def query(): # 获取url地址里面key值对应的value值; id = request.args.get('id') name = request.args.get('name') return "id: %s, name: %s" %(id, name) app.run()</user></id>
##Reverse URL
Get HTTP request data
Client passes URL When accessing the server program, two types of messages will be sent to the server, one is the HTTP request header, and the other is the request data.
1. 常见HTTP请求方法: GET: 1). 获取信息 2). 提交的信息会展示在url: http://www.wewtos.org/login?user=sheen&passwd=star POST:1). 提交信息, 不在url里面展示, 有利于数据的安全性; 2. 默认路由接受的请求方法为_____get____? 如何指定接收多个HTTP请求方法? 路由: @app.route('/login/', methods=['GET', 'POST']) 视图函数: def login(): 3. 如何判断用户请求的HTTP方法? request.method 如何获取用户POST请求提交的表单数据? request.form['user'] 4. 模板渲染(jinja2): why? python中生成html不易修改与维护, 所以将html的内容独立到templates目录中; how? 1). 去当前项目目录下寻找templtes是否存在?再去判断templates目录下是否有login.html文件? 2). 读取这个login.html文件的内容, 作为render_template的返回值; 3). 最终返回给用户浏览器; render_template('login.html') 5. 重定向和错误? redirect return render_template('login.html', message="用户名或者密码错误")
Example: Login jump
#这里的index.html、login.html、404.html是需要自己提前写好的可访问网页 #所有的模板需要放在templates目录下 from flask import Flask, request, render_template, redirect, url_for, abort app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': print(request.form) # 1. 如何获取到用户提交的信息呢? user = request.form['user'] passwd = request.form['passwd'] # 2. 判断用户名和密码是否正确 if user == 'root' and passwd =='sheen': # 如果登陆成功, 跳转到主页; return redirect(url_for('index')) else: # 如果登陆失败, 重新登陆; return render_template('login.html', message="用户名或者密码错误") else: # 用户是GET请求, 返回登陆的html页面 # 1. 读取login.html文件的内容 # 2. 将读取的内容返回给用户界面 return render_template('login.html') # 404异常处理: 类似于捕获异常 @app.errorhandler(404) def not_found(e): return render_template('404.html') # 抛出异常 @app.route('/user/<user_id>/') def user(user_id): if 0<int app.run><h1></h1> <p style="text-align: center;"><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/438/648/136/1540373077718507.png?x-oss-process=image/resize,p_40" class="lazy" title="1540373077718507.png" alt="Detailed explanation of Web framework (Flask) in python (code example)"><br></span></p> <p style="text-align: center;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/410/199/933/1540373095508604.png?x-oss-process=image/resize,p_40" class="lazy" title="1540373095508604.png" alt="Detailed explanation of Web framework (Flask) in python (code example)"><span class="img-wrap"> </span>##</p></int></user_id>
The above is the detailed content of Detailed explanation of Web framework (Flask) in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools