服务器程序
import flask
app = flask.Flask(__name__)
# 访问"http://127.0.0.1:5000/",可以返回get和post传过来的数据
@app.route('/') # 默认只接收get请求,@app.route('/',methods=["GET","POST"])或者只写"POST",同时接收两种请求
def index():
try:
# flask.request.args 存有get的参数,flask.request.form 存有post的参数
# flask.request.values 既有get参数,也有post参数,通用。if 避免了数据不存在造成的出错
province = 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 f"{province},{city}\n{note}"
except Exception as err:
return str(err)
@app.route('/hi') # 访问"http://127.0.0.1:5000/hi"可以返回index.html文件的网页
def hi():
try:
f = open("index.html", 'rb')
data = f.read()
f.close()
return data
except Exception as err:
return str(err)
# 访问"http://127.0.0.1:5000/image",返回图像的名字,如果带上fileName参数访问,返回图像数据或者空值(不存在时)
@app.route('/image')
def image():
if "fileName" not in flask.request.values:
return "1.jpg"
else:
data = b""
try:
fileName = flask.request.values.get("fileName")
if fileName != "" and os.path.exists(fileName):
f = open(fileName, "rb")
data = f.read()
f.close()
except Exception as err:
data = str(err).encode()
return data
# 上传文件
@app.route('/upload', methods=["POST"])
def uploadFile():
msg = ""
try:
if "fileName" in flask.request.values: # get参数有fileName
fileName = flask.request.values.get("fileName")
file = flask.request.files["file"] # 得到文件对象
file.save("upload"+file.filename)
msg = "ok"
else:
msg ='没有按要求上传文件'
except Exception as err:
print(err)
return str(msg)
if __name__ == '__main__':
app.run()
客户端程序
import requests
province = "广东"
city = "深圳"
note = "大段文字......"
url = f"http://127.0.0.1:5000/?province={province}&city={city}" #get传送数据
data = {"note": note} # post传送数据
resp = requests.post(url, data= data)
print(resp.content.decode())
# url = "http://127.0.0.1:5000/image" #下载图片
# resp = requests.get(url)
# fileName = resp.content.decode() # 得到图像的名字
# resp = requests.get(f"{url}?fileName={fileName}") # 图像名字作为数据
# with open("2.jpg", "wb") as f:
# f.write(resp.content)
# url = "http://127.0.0.1:5000/upload" # 上传文件
# uploadFileName = input("Enter the file:")
# if os.path.exists(uploadFileName):
# with open(uploadFileName, 'rb') as f:
# dataB = f.read()
# dataDict = {"file": (uploadFileName, dataB, "application/octet-stream")}
# resp = requests.post(f"{url}?fileName={uploadFileName}", files=dataDict) # 文件上传是post
# msg = resp.content.decode()
# if msg == "ok":
# print("成功上传:", len(dataB), "字节")
# else:
# print(msg)
# else:
# print("文件不存在!")
html文件
Welcomd Python Flask Web
it is very easy tomake a website by Python Flask中文