Absolute Dry, Instances take you through the flask framework of python-web

Ridiculous _Recently, I haven't coded for a l...
Ridiculous
Simple try
Advanced Use
Postnote

Ridiculous

_Recently, I haven't coded for a long time. I think it's time to write a summary article, but I haven't found anything to write for a long time.Then flip over the blog I wrote before, as if there were no articles about python-web at all, so start with this one.

I started with the idea of setting up my own blog when I always wanted to have a website with cool hanging days, but how to set up a website with what to do was confusing and stumbling for more than half a month was a foggy start.

_As far as I know, the python-web framework has flask and django, but the difference between them is not very clear to me. I have not used django, but I just know flask and Django with great emotion. In my opinion, one is like a rough room, the other is a hardcover room, and see my personal preferences.


_First of all, I prefer to toss and roll, so flask is definitely the preferred choice. It has high plasticity and is easy to use.Moreover, it is not because of poverty!Look at this hardcover room, look at this accessory, how advanced!

_Ha-ha, kidding, in fact, because looking at the source comparison between the two, it seems flask is more concise and clear, head will not bald so quickly.

_OK, to get to the point, I'll use flask to make some summaries, and finally I'll give you a general overview of how to run flask on a cloud server and lay out a website.

Simple try

_Needless to say the first step is pip install flask, which is faster to use from domestic sources.

pip install -i https://pypi.doubanio.com/simple

_Next, look at the diagram.

#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/6 19:55 # @Author : Cxk # @File : run.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello Cxk! if __name__ == '__main__': app.run(debug=True)

_You can see that characters can be displayed on a web page in just a few steps, which are roughly divided into four steps: importing packages, creating instances, creating routing functions, and calling instances.
_Here I'll just tell you what a route is. In fact, it's a decorator, @app.route('/'), which binds functions to a fixed url, such as now ('/'), defaulting to http://127.0.0.1:5000/home page. When we add a name to it, it doesn't show up when you open http://127.0.0.1:5000/For example, let's create @app.route('/cxk'), and let's try again.

Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

_Not surprisingly, we changed the default route to ('/cxk') Open Page Display found No.And when we add / cxk manually, we can see that we are back to the home page just now. In fact, the route is used to distinguish different pages. Let's try to return to a web page again. We just returned a string.
_First set up under the project file, two folders, one static, one templates._Static is a folder for static files, templates is a folder for source code of web pages, statics are not needed for the time being, first create a web page file index.html under templates.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello,CXk! </body> </html>

_Then we'll change the source code and add a render_template template template.

#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/6 19:55 # @Author : Cxk # @File : run.py from flask import Flask, render_template app = Flask(__name__ @app.route('/') def index(): return render_template('index.html') @app.route('/cxk') def cxk(): return 'Hello,CXk!' if __name__ == '__main__': app.run(debug=True)



_Did you find that although the two words are the same, the font on the web page looks good, and there is a title at the top of the web page, which returns the string title directly to give you a url name, while the web page is set by itself

Advanced Use

_With the above foundation, we can do something more meaningful, interfaces.Here, I take three-terminal login as an example. The so-called three-terminal is Web, pc, WeChat applet, corresponding - Web, computer, mobile phone.

Set Interface

_I forgot to mention front-end and back-end data transfer above. Here I add two parameters to pass pages and display my account on the front-end page:, password:, which corresponds to each other on the page
{}, {}, the fact is so simple, {{}}, two braces, want to know more about your own Baidu.

_I directly judge that if the account password is 123456 then the login will succeed and vice versa it will fail.Return is json format data, on the web we can actually go back to other pages directly, but in order to handle with the applet on the pc side, it is better to return to json format here.

<input id="username" type="text" name='username' autocomplete="off" placeholder={{name}}> <input id="password" type="password" name='password' autocomplete="off" placeholder={{password}}>
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/6 19:55 # @Author : Cxk # @File : run.py from flask import Flask, render_template,request import json app = Flask(__name__) @app.route('/') def index(): name='Account number:' password='Password:' return render_template('index.html',name=name,password=password) @app.route('/login', methods=['POST']) def login(): try: # Applet Gets post Data if request.data: data = request.data.decode('utf-8') data_json = json.loads(data) username = data_json['username'] password = data_json['password'] #Web page and PC side else: username = request.form.get('username') password = request.form.get('password') if username == '123456' and password == '123456': return json.dumps({"code":200,"msg": "Login Successful"},ensure_ascii=False) else: return json.dumps({"code": 404, "msg": "Logon Failure"}, ensure_ascii=False) except: return json.dumps({"code": 500, "msg": "Background error"}, ensure_ascii=False) if __name__ == '__main__': app.run(debug=True)

Web side

_This is a freely found login interface on my web. It looks good. I have changed it myself. The picture resources are placed in the images folder under static. Here are three resource files, backgroud.png, password.png, login.png, emil.png.



<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>Sign in</title> <style> * { margin: 0; padding: 0; } html { height: 100%; } body { height: 100%; background: #fff url(static/images/backgroud.png) 50% 50% no-repeat; background-size: cover;} .dowebok { position: absolute; left: 50%; top: 50%; width: 430px; height: 550px; margin: -300px 0 0 -215px; border: 1px solid #fff; border-radius: 20px; overflow: hidden;} .logo { width: 75px; height: 75px; margin: 50px auto 50px; background: url(static/images/login.png) 0 0 no-repeat; } .form-item { position: relative; width: 360px; margin: 0 auto; padding-bottom: 30px;} .form-item input { width: 288px; height: 48px; padding-left: 70px; border: 1px solid #fff; border-radius: 25px; font-size: 18px; color: #fff; background-color: transparent; outline: none;} .form-item button { width: 360px; height: 50px; border: 0; border-radius: 25px; font-size: 18px; color: #1f6f4a; outline: none; cursor: pointer; background-color: #fff; } #username { background: url(static/images/emil.png) 11px 3px no-repeat; } #password { background: url(static/images/password.png) 11px 3px no-repeat; } .reg-bar { width: 360px; margin: 20px auto 0; font-size: 14px; overflow: hidden;} .reg-bar a { color: #fff; text-decoration: none; } .reg-bar a:hover { text-decoration: underline; } .reg-bar .reg { float: left; } .reg-bar .forget { float: right; } .dowebok ::-webkit-input-placeholder { font-size: 18px; line-height: 1.4; color: #fff;} .dowebok :-moz-placeholder { font-size: 18px; line-height: 1.4; color: #fff;} .dowebok ::-moz-placeholder { font-size: 18px; line-height: 1.4; color: #fff;} .dowebok :-ms-input-placeholder { font-size: 18px; line-height: 1.4; color: #fff;} @media screen and (max-width: 500px) { * { box-sizing: border-box; } .dowebok { position: static; width: auto; height: auto; margin: 0 30px; border: 0; border-radius: 0; } .logo { margin: 50px auto; } .form-item { width: auto; } .form-item input, .form-item button, .reg-bar { width: 100%; } } </style> </head> <body> <div> <div></div> <form action="login" method="post"> <div> <input id="username" type="text" name='username' autocomplete="off" placeholder={}> </div> <div> <input id="password" type="password" name='password' autocomplete="off" placeholder={}> </div> <div><button id="submit">Sign in</button></div> </form> </div> <script src="static/js/jquery.min.js"></script> </body> </html>
Effect Display

pc end

_Here I use the previously written face recognition login interface. Interesting Click on Portal.

# -*- coding:utf-8 -*- #!/usr/bin/env python # @Time : 2020/5/6 19:55 # @Author : Cxk # @File : login.py from tkinter.messagebox import * from tkinter import * import requests class LoginPage(object): def __init__(self, master=None): self.root = master winWidth = 650 winHeight = 400 screenWidth = self.root.winfo_screenwidth() screenHeight = self.root.winfo_screenheight() x = int((screenWidth - winWidth) / 2) y = int((screenHeight - winHeight) / 2) # Set the initial position of the window to center on the screen self.root.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y)) # Set window icon # root.iconbitmap("./image/icon.ico") # Set window width and height fixed self.root.resizable(0, 0) self.student_number = StringVar() self.student_pw = StringVar() self.createPage() def createPage(self): ''' //Logon Page 1:Create Picture Component 2:Add based on root directory Frame container 3:Frame Add Register Control to Container ''' bm=PhotoImage(file=r'cxk.gif') self.lab3=Label(self.root,image=bm) self.lab3.bm=bm self.lab3.pack() self.page = Frame(self.root) self.page.pack() Label(self.page).grid(row=0, stick=W) Label(self.page, text = ' School Number:').grid(row=1, column=0,stick=W, pady=10) Entry(self.page, textvariable=self.student_number).grid(row=1, column=1, stick=E) Label(self.page, text = ' Password:').grid(row=2, column=0,stick=W, pady=10) Entry(self.page, textvariable=self.student_pw, show='*').grid(row=2, column=1, stick=E) Button(self.page, text='Student Login', command=self.student_loginCheck).grid(row=3,column=1) def student_loginCheck(self): try: Student_number=self.student_number.get() Student_pw=self.student_pw.get() if Student_number=="" or Student_pw=="": showinfo(title="error",message='Account number and password cannot be empty!') else: data={ 'username':Student_number, 'password':Student_pw } res=requests.post('http://127.0.0.1:5000/login',data) if (res.json()['code']==200): self.page.destroy() self.lab3.pack_forget() StudentPage(self.root) else: showinfo(title='error',message='%s'%res.json()['msg']) except: showinfo(title='error',message='Unknown error!') class StudentPage(object): def __init__(self, master=None): self.root = master #Define the internal variable root self.root.geometry('%dx%d' % (650, 400)) #Set window size self.root.resizable(0,0) #Prevent users from resizing self.createPage() def createPage(self): self.menuPage = MenuFrame(self.root) # Create different frames class MenuFrame(Frame): # Inherit Frame Class def __init__(self, master=None): Frame.__init__(self, master) self.root = master #Define the internal variable root self.createPage() def createPage(self): strs="Login successful!" Label(self.root,text=strs,font=("Arial", 30)).pack() root = Tk() #Create a root window, the base of all windows root.title('Student Management System') LoginPage(root)#Enter Call Login root.mainloop()
Effect Display

Key Code Explanation

_We first get the character of the front-end input box, and then take the character to requests.post to submit the request. Why post instead of get? Looking at the previous code, I set methods=['POST'] at the interface to indicate that only post requests are accepted there, while the general account password is post requests, because post requests do not appear in the url, I want to know more about Baidu by myselfPost and get, respectively.Then we can make a decision based on the "code" in the json data returned by the server interface. 200 means the request is successfully logged in and see how your interface is set.
_Note that we need to run the source code of the web page before we can find the requested one.

Student_number=self.student_number.get() Student_pw=self.student_pw.get() if Student_number=="" or Student_pw=="": showinfo(title="error",message='Account number and password cannot be empty!') else: data={ 'username':Student_number, 'password':Student_pw } res=requests.post('http://127.0.0.1:5000/login',data) if (res.json()['code']==200): self.page.destroy() self.lab3.pack_forget() StudentPage(self.root) else: showinfo(title='error',message='%s'%res.json()['msg'])

WeChat Applet

js

//index.js //Get Application Instances const app = getApp() Page({ data: { name:'', password:'' }, name(e){ this.setData({ name: e.detail.value }) }, password(e){ this.setData({ password: e.detail.value }) }, formSubmit: function () { wx.request({ url: 'http://127.0.0.1:5000/login', data: { username: this.data.name, password: this.data.password }, method: 'post', header: { 'content-type': 'application/json' }, success: function (res) { var msg=JSON.parse(res.data) wx.showModal({ title: 'Tips', content: msg['msg'], }) } }) } , onLoad: function () { }, }

wxml

<view> <view> <text>Logon Attempts</text> </view> <view> <text>Account number:</text> <input type='number' placeholder='Please enter a number' bindinput ="name"/> </view> <view> <text>Password:</text> <input password='true' placeholder='Please input a password' bindinput ="password"/> </view> <view> <button type='primary' form-type='submit' bindtap="formSubmit" >Sign in</button> </view> </view>

wxss

/**index.wxss**/ input{ border: 1px solid #ccc; width: 310px; height: 40px; } .button{ margin-top: 20px; } .header text{ font-size: 25px; color: #666; }
Effect Display

Postnote

_At this point, we have a basic understanding of flask's 7788, what remains is a bunch of detailed operations and high-end use. Learn a little bit, and slowly we will compare things. In fact, many times I tap to get started. For example, this article, in fact, I also understand while tapping. Before I tried the three-end-in-one interface, I thought I should be able, and then I started.Try it, but the data format is a problem. The data submitted by the applet is inconsistent with that submitted by the pc on the web page. It has been here for a long time.It's a pit. Finally, I can't tell by using if. The big man is grateful for the message that he knows what's wrong.

Triumph in Triumph Original Article 47 Praise 58 Visits 40,000+ follow Private letter

6 May 2020, 12:37 | Views: 7576

Add new comment

For adding a comment, please log in
or create account

0 comments