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)

猜你喜欢

转载自www.cnblogs.com/Su-feng-address/p/10198379.html