1. 程式人生 > >Pycharm中flask框架應用

Pycharm中flask框架應用

flask框架應用例項

get方法

伺服器端 server.py 如下

import flask
app=flask.Flask(_name_)  
//啟動一個應用程式

@app.rout("/")
//路由的作用
def hello():
//定義一個函式
try: province=flask.request.args.get("province") if "province" in flask.request.args else "" city=flask.request.args.get("city") if "city" in flask.request.args else
"" return province+","+city except Exception as err: return str(err) @app.rout("/hi") def hello(): return “hello” if _name_=="_main_": app.run()

 

 

客戶端 client.py如下

import urllib.parse
import urllib.request

//瀏覽器訪問 url
="http://127.0.0.1:5000" try:
//漢字編碼為十六進位制 province
=urllib.parse.quote("
廣東") city=urllib.parse.quote("深圳") data="province="+province+"&city="+city
//向伺服器端傳送,並將伺服器返回結果儲存在html中 html
=urllib.request.urlopen("http://127.0.0.1:5000?"+data) html=html.read() html=html.decode() print(html) except Exception as err print(err)

 

post方法

伺服器端 server.py 如下

import flask
@app.route(
"/",methods=["post"]) def index(): try: province=flask.request.form.get("province") if "province" in flask.request.form else "" city=flask.request.form.get("city") if "city" in flask.request.form else "" return province+","+city except Exceptioin as err: return str(err) if _name_=="_main_": app.run()

 

客戶端client.py如下

import urllib.parse
import urllib.request
url="http://127.0.0.1:5000"
try:
province=urllib.parse.quote("廣東")
city=urllib.parse.quote("深圳")
data="province="+province+"&city="+city
data=data.encode()
html=urllib.request.urlopen("http://127.0.0.1:5000",data=data)
html=html.read()
html=html.decode()
print(html)
except Exception as err:
print(err)

 

混合

伺服器端程式碼

import flask
app.flask.Flask(_name_)
@app.route("/",methods=["GET","POST"])
def index(): 
try:
provice=flask.request.args.get("province") if "province" in flask.request.args else ""
city=flask.request.args.get("city") if "city" in flask.request.args else ""
note=flask.request.args.form.get("note") if "note" in flask.request.form else ""
return  province+","+city+"\n"+note
except Exception as err:
return str(err)

if _name_=="_main_":
app.run()

也可以

import flask
app.flask.Flask(_name_)
@app.route("/",methods=["GET","POST"])
def index(): 
try:
provice=flask.request.values.get("province") if "province" in flask.request.values else ""
city=flask.request.values.get("city") if "city" in flask.request.values else ""
note=flask.request.values.get("note") if "note" in flask.request.values else ""
return  province+","+city+"\n"+note
except Exception as err:
return str(err)

if _name_=="_main_":
app.run()

 

客戶端程式碼

import urllib.parse
import urllib.request
url="http://127.0.0.1:5000"
note="深圳依山傍海,氣候宜人,...."
try:
provice=urllib.parse.quote("廣東")
city=urllib.parse.quote(note)
param="province="+province+"&city="+city
html=urllib.request.urlopen("http://127.0.0.1:5000?"+param,data=note.encode())
html=html.read()
html=html.decode()
print(html)
except Exception as err:
print(err)

 

flask預設伺服器埠號 5000

瀏覽器訪問

http://127.0.0.1:5000

 

web檔案下載

伺服器端程式碼

import flask
import os
app=flask.Flask(_name_)
@app.route("/")
def index():
if  not "fileName"  in flask.request.values:
s="影象.jpg"
return s
else:
fileName=request.values.get("fileName")
f=open(fileName,"rb")
data=f.read()
f.close()
return data
app.run()

客戶端程式碼

import urllib.parse
import urllib.request
url="http://127.0.0.1:5000"
resp=urllib.request.urlopen(url)
data=resp.read()
fileName=data.decode()
data=urllib.request.urlopen(url+"?fileName="+urllib.parse.quote(fileName))
data=data.read()
fobj=open("download"+fileName,"Wb")
fobj.write(data)
fobj.close()
print(fileName,len(data))
except Exception as err:
print(err)

 

web檔案上傳

伺服器端程式碼

 

import flask
import os
app=flask.Flask(_name_)
@app.route("/upload",methods=["POST"])
def uploadFile():
msg=""
try:
if "fileName" in flask.request.values:
fileName=flask.request.values.get("fileName")
data=flask.request.get_data()
fobj=open("unload"+fileName,"wb")
fobj.write(data)
fobj.close()
msg="OK"
else:
msg="沒有按要求上傳檔案" 
except Exception as err:
print(err)
msg=str(err)
return msg 

 

 

 

客戶端程式碼

 

import urllib request
import os
url="http://127.0.0.1:5000/upload"
fileName="《Phython web程式開發技術》教材.pdf"
try:
fobj=open(fileName,"rb")
data=fobj.read()
fobj.close()
headers={'content-type': 'application/octet-stream'} 
url=url+"?fileName="+urllib.parse.quote(fileName)
req=urllib.request.Request(url,data,headers)
resp=urllib.request.urlopen(req)
msg=resp.read().decode()
print(msg)
except Exceptioin as e:
print(e)

 與資料互動

首先伺服器端與客戶端形成約定,

 

並,在Sqlite資料庫中,建立表,

建立維護一個Sqllite的學生庫Students.db中的學生記錄表
creat table students(
No varchar(16) primary key,
Name varchar(16),
Sex varchar(8)
Age int);

伺服器端程式碼

 

import flask
import sqlite3
import jspn
app=flask.Flask(_name_)

//通過類StudentDB開啟Sqlit3資料庫紅students.db
class StudentDB: def openDB(self)
//連線資料庫 self.con
=sqlit3.connect("students.db")
//獲取遊標 self.cursor
=self.con.cursor() def closeDB(self):
//資料庫提交 self.con.commit()
//資料庫連線關閉 self.con.close()
def initTable(self): res={} try: self.cursor.execute("create table students( No varchar(16) primary key,Name varchar(16), Sex varchar(8),Age int)") res["msg"]="OK" except Exception as err: res["msg"]=str(err) return res def insertRow(self,No,Name,Sex,Age): res={} try: self.cursor.execute("insert students(No,Name,Sex,Age) values(?,?,?,?)" values(No,Name,Sex,Age)) res["msg"]="OK" except Exception as err: res["msg"]=str(errd) def deleteRow(self.No): res={} try: self.cursor.execute("delete from students where No=?",(No,)) res["msg"]="OK" except Exception as err: res["msg"]=str(err) return res def selectRows(self): res={} try: data=[] self.cursor.execute("select * from students order by No") rows.self.cursor.fetchall() for row in rows: d={} d["No"]=row[0] d["Name"]=row[1] d["Sex"]=row[2] d["Age"]=row[3] data.append(d) res["msg"]="ok" res["data"]=data execept Exception as err: res["msg"]=str(err) return res @app.route("/",methods=["GET","POST"]) def process(): opt=flask.request.values.get("opt") if "opt" in flask.request.values else "" res={} db=StudentDB() db.openDB() if opt=="init" : res=db.initTable() elif opt=="insert": No=flask.request.values.get("No") if "No" in flask.request.values else "" Name=flask.request.values.get("Name") if "No" in flask.request.values else "" Sex=flask.request.values.get("Sex") if "Sex" in flask.request.values else "" Age=flask.request.values.get("Age") if "No" in flask.request.values else "" res=db.insertRow(No,Name,Sex,Age) elif opt=="delete": No=flask.request.values.get("No") if No in flask.request.values else "" res=db.deleteRow(No) else: res=db.closeDB() return json.dumps(res) if _name_=="_main_" app.run()

 

客戶端程式碼

 

import urllib.request
import json
class Student:

def _init_(self,No,Name,Sex,Age):
self.NO=No
self.Name=Name
self.Sex=sex
self.Age=age

def.show(self)
print("%-16s%-16s%-8s%-4d"%(self.No,self.Name,self.Sex,self.Age))
students=[]
url="http://127.0.0.1:5000"

def listStudents():
global students
print("%-16s%-16s%-8s%-4d"%(self.No,self.Name,self.Sex,self.Age))
for s in students:
s.show()

def insertStudent(s)
global students
i=0
while(i<len(students)and s.No>students[i].No):
i=i+1
if(i<len(students) and s.No==students[i].No):
print(s.No+"already exists")
return False
students.insert(i,s)
return True

def deleteRow():
global students
No=input("No=")
if(No!=""):
for i in range(len(students)):
if(students[i].No==No):
st=""
try:
st="No="+urllib.request.quote(No)
st=st.encode()
content=urllib.request.urlopen(url+"?opt=delete",st)
st=content.readline()
st=json.loads(st.decode)
st=st["msg"]
except Exception as exp:
st=str(exp)
if(st=="OK")
del students[i]
print("刪除成功")
else:
print(st)
break

def insertRow():
No =input("No=")
Name=input("Name=")
while True:
Sex=input("Sex=")
if(Sex=="" or Sex==""):
break
else:
print("Sex is not valid")
Age = input("Age=")
if(Age==""):
Age=0
else:
Age=int(Age)
if(Age<120 and Age>0):
break
else :
print("Age is go wrong")
if (No!="" and Name !=""):
s=Student(No,Name,Sex,Age)
for x in students:
if(x.No==No)
print(No+"already exists")
return
st=""
try:
st="No="+urllib.request.quote(No)+"&Name="+urllib.request.quote(Name)+"&Sex="+urllib.request.quote(Sex)+"&Age="+str(Age)
st=st.encode()
content=urllib.request.urlopen(url+"?opt=insert",st)
st=content.read()
st=json.loads(st.decode)
st=st["msg"]
except Exception as exp:
st=str(exp)
if(st=="OK"):
inserStudents(s)
print("增加成功")
else:
print(st)
else:
print("學號,姓名不能為空")

def readStudents():
global students
try:
students.clear()
content=urllib.request.urlopen(url)
data=b""
while True:
buf=content.read(1024)
if(len(buf)>0):
data=data+buf
else:
break
data=data.decode()
data=json.loads(data)
if(data["msg"]=="OK"):
data=data["data"]
for d in data
#each d is a dictionary
s=Student(d["No"],d["Name"]),d["Sex"],d["Age"])
students.append(s)
except Exception as exp:
print(exp)
try:
readStudents()
while True:
print("")
print("學生名單")
print("0.初始化學生列表")
print("1.檢視化學生列表")
print("2.增加學生列表")
print("3.刪除學生列表")

print("4 退出程式")

s=input("請選擇(0,1,2,3,4)")

if(s=="0"):
initialize()
elif(s=="1")
listStudents()
elif(s=="2")
insertRow()
elif(s=="3")
deleteRow()
elif(s=="4")
break
except Exception as exp:
print(exp)