Introduction to the Python Web Framework Flask Web site Development Example _python

Source: Internet
Author: User

Introduction of Flask

Flask is a Python-implemented WEB development micro-framework. Official website: http://flask.pocoo.org/

Second, Demo

1, Code structure

Copy Code code as follows:

.
├──blog.py
├──static
│├──css
││└──index.css
│├──images
││├──cat.jpg
││└──sheying1229.jpg
│└──js
└──templates
├──index.html
├──login.html
├──regist.html
└──upload.html

5 directories, 8 files

2, the main program blog.py

Copy Code code as follows:

#!/usr/bin/python
#coding: UTF8

From flask import flask, render_template, url_for, request,redirect,make_response,session
Import Os,mysqldb

App = Flask (__name__)
app.secret_key= ' AFJLSJFOWFLAJFLKAJFKJFKALJF '
User_list = [' Jim ', ' Max ', ' py ']

ImagePath = Os.path.join (OS.GETCWD (), "Static/images")

@app. Route ('/')
def index ():
Username = request.cookies.get (' username ')
If not username:
Username = U ' Please login first '
IsLogin = Session.get (' IsLogin ')
Nav_list = [u ' homepage ', u ' economy ', u ' culture ', U ' technology ', U ' entertainment ']
Blog = {' title ': ' Welcome to my blog ', ' content ': ' Hello, Welcome to my blog. '}
Blogtag = {' JavaScript ': ten, "Python": "Shell": 5}
img = url_for (' Static ', filename= "images/cat.jpg")
Return render_template (' index.html ', nav_list=nav_list, username=username, blog = blog, Blogtag = Blogtag, img=img, Islog In=islogin)

@app. Route ('/reg ', methods=[' get ', ' POST '])
def regist ():
if Request.method = = ' POST ':
Username = request.form[' username ']
conn = MySQLdb.connect (user= ' root ', passwd= ' admin ', host= ' 127.0.0.1 ')
conn.select_db (' blog ')
Curr = Conn.cursor ()
sql = ' INSERT INTO ' user ' (' id ', ' username ') values (%d, '%s ') '% (1,username)
Curr.execute (SQL)
Conn.commit ()
Curr.close ()
Conn.close ()
Return "User%s regist ok!"% request.form[' username ']
Else
#request. args[' username ']
Return render_template (' regist.html ')

@app. Route ('/upload ', methods=[' get ', ' POST '])
def upload ():
if Request.method = = ' POST ':
Username = request.form[' username ']
FILE = Request.files[' img ']
filename = File.filename
File.save (Os.path.join (imagepath,filename))
Return "Else
Return render_template (' upload.html ')

@app. Route ('/login/', methods=[' get ', ' POST '])
def login ():
if Request.method = = ' POST ':
Username = request.form.get (' username ')
If username in user_list:
Response = Make_response (redirect ('/'))
Response.set_cookie (' username ', value=username, max_age=300)
session[' islogin '] = ' 1 '
return response
Else
session[' islogin '] = ' 0 '
Return redirect ('/login/')
Else
Return render_template (' login.html ')

if __name__ = = ' __main__ ':
App.run (debug=true,host= ' 0.0.0.0 ', port=5000)

Main home, registration, login, upload page.

Blog.py mainly shows the common functional usage in flask: routing, database operation, Cookie,session,redirect, form, file uploading, debugging, IP and port of Web server, static file reading, etc.

3, homepage template index.html

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title>flask demo</title>
<link rel= "stylesheet" type= "Text/css" href= "Static/css/index.css"/>
<body>
<div class= "Header" >
{%if IsLogin = = ' 1 '%}
{%else%}
{%endif%}
<div class= "NAV" >
<ul>
{%for nav in nav_list%}
<li><a href= ' {nav}} ' >{{nav}}</a></li>
{%endfor%}
</ul>
</div>
</div>
<div class= "Container" >
<div class= "Item" >
<div class= "Content" >

<p>{{blog[' content ']}}</p>

</div>
</div>
<div class= "Side" >
<ul>
{%for key,value in Blogtag.items ()%}
<li>{{key}} ({{value}}) </li>
{%endfor%}
</ul>
</div>
</div>
</body>

This template mainly shows how to read variables of various types in the flask template.

4, login page login.html

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title>Login</title>
<link rel= "stylesheet" type= "Text/css" href= "Static/css/index.css"/>
<body>
<div class= "Header" >
</div>
<div class= "Container" >
<div class= "Item" >
<form action= "" method= "POST" >
<input type= "text" placeholder= "Please input username" name= "username"/><br/>
<input type= "Submit" value= "Login"/>
</form>
</div>
</div>
</body>

Combining blog.py mainly shows how the form submits values, cookies and session applications.

5, registration page regist.html

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title>Regist</title>
<link rel= "stylesheet" type= "Text/css" href= "Static/css/index.css"/>
<body>
<div class= "Header" >
</div>
<div class= "Container" >
<div class= "Item" >
<form action= "" method= "POST" >
<input type= "text" placeholder= "Please input username" name= "username"/><br/>
<input type= "Submit" value= "Regist"/>
</form>
</div>
</div>
</body>

The combination of blog.py mainly shows the database operation.

6, upload page upload.html

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8"/>
<title>Upload</title>
<link rel= "stylesheet" type= "Text/css" href= "Static/css/index.css"/>
<body>
<div class= "Header" >
</div>
<div class= "Container" >
<div class= "Item" >
<form action= "" method= "Post" enctype= "Multipart/form-data" >
<input type= "text" name= "username"/><br/>
<input type= "file" Name= "img"/><br/>
<input type= "Submit" value= "Upload"/>
</form>
</div>
</div>
</body>

Combined blog.py mainly shows how to upload files.

7. Operation Effect

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.