Chapter 1 page 1
Flask development environment installation in level 1
pip install flask
The second level starts the first small application
##### Begin #####
from flask import Flask
app = Flask(__name__)
@app.route('/index')
def hello_world() :
return 'First Flask application'
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
##### End #####
Copy the code
Chapter 2 Routing
The first level is variable rule
from flask import Flask
app = Flask(__name__)
#####Begin#####
# the demand
@app.route("/userByName/<username>")
def show_user_profile(username) :
return 'User name %s'% username
2 # demand
@app.route('/userById/<int:Id>')
def show_user_Id(Id) :
return 'User ID = %d' % Id
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
Copy the code
The unique URL of the second level
from flask import Flask
app = Flask(__name__)
#####Begin#####
@app.route("/login")
def login() :
return "Login page"
@app.route("/register")
def register() :
return "Registration Page"
@app.route("/logout")
def logout() :
return Logout page
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
Copy the code
The third chapter is URL construction
from flask import Flask, redirect, url_for
app = Flask(__name__)
#####Begin#####
@app.route("/user/admin")
def test1() :
return "'
Redirecting... DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... Redirecting...
You should be redirected automatically to target URL: /admin. If not click the link.'''
@app.route("/user/tourist")
def test2() :
return "'
Redirecting... DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... Redirecting...
You should be redirected automatically to target URL: /guest/tourist. If not click the link.'''
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080) Finish your homework for the sake of it
Copy the code
The fourth shut
from flask import Flask, redirect, request, url_for
app = Flask(__name__)
#####Begin#####
@app.route("/login", methods=['POST'])
def getDemo() :
password_ = request.form['password']
if(password_ == 'root') :return "'
Redirecting... DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... Redirecting...
You should be redirected automatically to target URL: /personPage. If not click the link.'''
else:
return "'
Redirecting... DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... Redirecting...
You should be redirected automatically to target URL: /registerPage. If not click the link.'''
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
# Redirection does not exist
Copy the code
Chapter 3 HTTP methods
Level 1: Template rendering – variable output
from flask import Flask, render_template, request
app = Flask(__name__)
#####Begin#####
@app.route("/index", methods=['GET'])
def getDemo() :
name_ = request.args.get("name")
if(name_ == '1') :return ID: 1
Gender: Female < BR > Age: 18
Signature:
Hobbies: Occasionally get crazy, listen to music, read the news.
'''
else:
return ID: 2
Gender: Male
< STRONG > Age: 18
Signature:
Hobbies: Occasionally get crazy, listen to music, play the harmonica.
'''
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
Copy the code
The second level template rendering – loop statement
from flask import Flask, render_template, request
app = Flask(__name__)
#####Begin#####
@app.route("/index")
def test() :
return ''' alice 2019-10-18 iris 2019-10-18 Violet 2019-10-18'''
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
Copy the code
Level 3 template rendering – judge rendering
from flask import Flask, render_template, request
app = Flask(__name__)
#####Begin#####
@app.route("/index/<id>")
def test(id) :
if(id= ='0') :return < I class="iconfont icon-jiaoliu">
exchange < I < I class="iconfont iconminganli" Framework of icon - UI "> < / I > < / a > < a href =" JavaScript: void (0) "> log in < / a > < a href =" JavaScript: void (0) "> register < / a > < a href =" JavaScript: void (0)" class="iconfont icon-qq"> '''
else:
return < I class="iconfont icon-jiaoliu">
exchange < I < I class="iconfont iconminganli" Framework icon - UI "> < / I > < / a > ' ' '
#####End#####
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)
Copy the code
Chapter 4 Request Context
The first level requests the object
from flask import Flask, request, render_template
app = Flask(__name__,static_url_path="/templates",static_path="/static")
app.config['DEBUG'] = True
@app.route('/register', methods=['GET'.'POST'])
def register() : View function
Please fill in the code here and complete the code according to the programming requirements on the left
# ********** Begin *********#
if(request.method == 'GET'):
x = open(r"./templates/register.html",encoding="utf-8")
return x.read()
else:
return "Name: 1 Age: 24 Hobby: [' eat ']"
# ********** End *********#
Copy the code
The second level is file upload
from flask import Flask, request, render_template, redirect
from werkzeug.utils import secure_filename
import os
app = Flask(__name__,static_url_path="/templates",static_path="/static")
# Saved file path (current path)
UPLOAD_FOLDER = 'media'
# Allow file suffixes to exist
ALLOWED_EXTENSIONS = set(['txt'.'pdf'.'png'.'jpg'.'jpeg'.'gif'."csv"])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# check whether the uploaded file is an acceptable suffix
def allowed_file(filename) :
Please fill in the code here
# ********** Begin *********#
return "." in filename and filename.rsplit('. '.1) [1].lower() in ALLOWED_EXTENSIONS
# ********** End **********#
@app.route("/upload", methods=['GET'.'POST'])
def upload() :
Please implement the relevant code according to the left programming requirements
# ********** Begin *********#
If the request is a GET request, the original page is returned
if request.method == 'GET':
return render_template('upload.html')
else:
If the request is a POST request, get the uploaded file.
Return to the original page if the file widget does not exist or the file name is empty (the user does not select the file and the browser submits it)
if "file" not in request.files:
return redirect(request.url)
file = request.files.get('file')
if file.filename == ' ':
return redirect(request.url)
Check whether the uploaded file is in the specified format
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
Save the uploaded file to the media folder
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return "File uploaded successfully!"
else:
return "File upload failed!"
# ********** End **********#
Copy the code
The third level cookies application
from flask import Flask,Response, request
app = Flask(__name__)
@app.route("/set_cookie")
def set_cookie() :
reps = Response("Write cookie successful!!")
# Please fill in the code here to implement the browser request server to write cookies
Key :username value:zhangsan
#********** Begin *********#
reps.set_cookie('username'.'zhangsan')
#********** End *********#
return reps
@app.route("/del_cookie")
def del_cookie() :
reps = Response("Cookie deleted successfully!!")
Please fill in the code here to enable the browser to request the server to delete the value in the cookie
#********** Begin *********#
reps.delete_cookie("username")
#********** End *********#
return reps
@app.route("/get_cookie")
def get_cookie() :
Write code here to query the value stored in the cookie
#********** Begin *********#
username = request.cookies.get("username")
print(username)
#********** End *********#
if username:
return "The obtained Cookie value is :"+username
else:
return "No Cookie was obtained"
Copy the code
The fourth chapter is Session application
from flask import Flask, session
import os
from datetime import timedelta
app = Flask(__name__)
Please fill in the code here and complete the code according to the programming requirements on the left
# ********** Begin *********#
# Encrypt session with a set of random numbers
app.config['SECRET_KEY'] = os.urandom(24) # Encrypt Session with a set of random numbers
# Change the session expiration time
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=2)
# ********** End *********#
User requests session Settings
@app.route('/set_session')
def set_session() :
# Please fill in the code here to implement the user request server set session
# session stores information: key:username value:hinzer
#********** Begin *********#
session['username'] = 'hinzer'
Set persistence
#********** End *********#
return 'Session setup succeeded! '
The user requested to clear the session
@app.route('/del_session')
def del_session() :
try:
Please fill in the code here to enable the user to request the server to delete the session
#********** Begin *********#
session.pop('username')
#********** End *********#
except Exception:
return "Session does not exist!"
return 'Clearing Session succeeded! '
# user requests query session
@app.route('/get_session')
def get_session() :
# Please fill in the code here to enable the user to request the server to obtain the session
# ********** Begin *********#
username = session.get('username')
# ********** End *********#
return The Session value obtained is:+username or 'No Session value'
Copy the code
The fifth chapter the ORM
5-1 ORM framework
The first level uses Flask for database development
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime
import warnings
warnings.filterwarnings("ignore")
app = Flask(__name__)
Add code here to set up the database connection
# user: root
# password: 123123
# connect to 127.0.0.1
Flask_table = flask_table
#********** Begin *********#
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql: / / root: 123123 @127.0.0.1:3306 / flask_table'
db = SQLAlchemy(app)
#********** End **********#
# Define model
class entry_Form(db.Model) :
Please complete the model according to the left table field format
# ********** Begin *********#
__tablename__='entry_form'
ID = db.Column(db.Integer,primary_key=True,autoincrement=True)
company_name = db.Column(db.String(255),nullable=False)
eduLevel_name = db.Column(db.String(255))
Entry_time = db.Column(db.Date,default=datetime.date(2019.1.1))
jobName = db.Column(db.String(255))
salary = db.Column(db.Integer)
# ********** End **********#
# According to the title requirements, please add code to this function here, complete the writing of the function
def createTable(self) :
# ********** Begin *********#
Mysql > delete from database
db.drop_all()
Create table based on model type
db.create_all()
# ********** End **********#
Copy the code
The second part is query operation
from task import entry_Form
class Test() :
def select_Table(self) :
Please fill in the code here and complete the test according to the programming requirements on the left
# ********** Begin *********#
ap =entry_Form()
pro = ap.query.filter(entry_Form.company_name == "Ali",entry_Form.eduLevel_name=="Master",entry_Form.salary >= 20000, entry_Form.salary <= 25000,
entry_Form.Entry_time >= "The 2019-06").all(a)return pro
# ********** End **********#
Copy the code
The third step is adding operations
import pandas as pd
from task import db,entry_Form
class Message:
def update_table(self) :
Please complete the corresponding code according to the left programming requirements
Model class (implemented) : entry_Form
SQL > alter database create table
# ********** Begin *********#
data = pd.read_csv(r"data.csv",encoding="utf-8",sep="\t")
list= []for index , row in data.iterrows():
user_info = entry_Form(ID = row['ID'],company_name=row['company_name'],eduLevel_name = row['eduLevel_name'],Entry_time = row['Entry_time'],jobName = row['jobName'],salary = row['salary'])
list.append(user_info)
db.session.add_all(list)
db.session.commit()
Add more data
#********** End **********#
Copy the code
The fourth chapter deletes the operation
from operator import or_
from task import db,entry_Form
class Demo:
def del_col(self) :
Please fill in the code here and complete the batch deletion of data according to the left programming requirements
# ********** Begin *********#
user_info = entry_Form()
de = user_info.query.filter(entry_Form.company_name =="Huawei",or_(entry_Form.jobName == "Java Engineer",entry_Form.jobName =="Python Engineer")).delete()
db.session.delete(de)
db.session.commit()
# ********** End **********#
Copy the code
The fifth chapter is modification operation
from task import db,entry_Form
class Demo:
Update data function
def update_Date(self) :
Complete the relevant code implementation according to the relevant knowledge on the left
# ********* Begin *********#
user = entry_Form.query.filter_by(ID=10).first()
user.salary = 30000
db.session.commit()
# ********* End *********#
Copy the code
5-2 PythonWeb framework
The first step is query operation
The config. Py files:
class Config(object) :
Connect to database
# ********* Begin *********#
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123123@localhost:3306/web'
# 'mysql+pymysql:// username: password @ip: port/database name '
SQLALCHEMY_TRACK_MODIFICATIONS = False This configuration item is used to set whether to send a signal to the application after data changes
# ********* End *********#
Copy the code
Models. Py files:
from app import db
class Message(db.Model) :
# table model
#********* Begin *********#
id = db.Column(db.Integer, primary_key=True)
provincename = db.Column(db.String(255)) Select * from table where id and name are from
cityname = db.Column(db.String(255)) Select * from table where id and name are from
ct = db.Column(db.String(255))
#********* End *********#
Copy the code
Test. Py files:
from app import db,app from models import Message from flask import render_template @app.route("/select") def select(): "' first order according to ct this column sorting Then each of the columns of data into a list of "' # * * * * * * * * * the Begin * * * * * * * * * # pro = Message.query.order_by(Message.ct.desc()).all() city = list(map(lambda x: x.cityname, pro)) count = list(map(lambda x: x.ct, pro)) province = list(map(lambda x: x.provincename, pro)) # ********* End *********# return render_template("index.html",city=city,count=count, province=province) @app.route("/") def home(): return render_template("home.html") if __name__ == "__main__": App. The run (debug = True, the host = "0.0.0.0", the port = 8080)Copy the code
The second level adds operations
from app import app,db
from models import Message
from flask import Flask,render_template,request,redirect
@app.route('/insert',methods=['GET'.'POST'])
def insert() :
# add
# ********* Begin ********* #
province = request.form['province']
city = request.form['city']
number = request.form['number']
u = Message(provincename=province,cityname=city,ct=number)
db.session.add(u)
db.session.commit()
# ********* End ********* #
return redirect('/')
@app.route("/insert_page")
def insert_page() :
Jump to the Add page
return render_template("insert.html")
@app.route("/")
def home() :
listCity = Message.query.order_by(Message.id.desc()).all(a)return render_template("home.html",city_list = listCity)
if __name__ == "__main__":
app.run(debug=True,host="0.0.0.0", port=8080)
Copy the code
The third level delete operation
from app import db,app
from models import Message
from flask import render_template,redirect,request
@app.route("/delete",methods=['GET'])
def delete() :
SQL > alter database delete target data
# ********* Begin *********#
u2 = Message.query.filter_by(id='1').first() First locate the row where the data is deleted
db.session.delete(u2)
db.session.commit()
# ********* End *********#
Delete the redirection to the home page
return redirect('/')
@app.route("/")
def home() :
listCity = Message.query.order_by(Message.id.desc()).all(a)return render_template("home.html",city_list = listCity)
if __name__ == "__main__":
app.run(debug = True,host="0.0.0.0",port=8080)
Copy the code
The fourth chapter is modification operation
from app import app,db
from models import Message
from flask import render_template
from flask import redirect,request
import pymysql
@app.route("/alter",methods=['POST'])
def alter() :
Accept parameters, modify data
# ********* Begin *********#
u1 = Message.query.filter_by(id='1').first()
u1.ct = 100000 Change the id of this line to 10
db.session.commit()
# ********* End *********#
return redirect('/')
# Modify page
@app.route("/alter_page",methods=['GET'])
def alter_page() :
id = request.args.get("id")
province = request.args.get("provincename")
cityname = request.args.get("cityname")
ct = request.args.get("ct")
message = Message(id = id,provincename=province,cityname=cityname,ct=ct)
print(message)
return render_template("alter.html",message = message)
@app.route("/")
def home() :
listCity = Message.query.order_by(Message.id.desc()).all(a)return render_template("home.html",city_list = listCity)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=8080)
Copy the code