使用POST方法向网站发送数据
POST方法向网站发送数据
server.py
import flask app = flask.Flask(__name__) @app.route('/', methods=['GET','POST']) def index(): try: province = flask.request.form.get('province') city = flask.request.form.get('city') note = flask.request.form.get('note') print(province, city, note) return province + "\n" + city + "\b" + note except Exception as e: print(e) debug = True if __name__ == '__main__': app.run()
client.py
import urllib.request import urllib.parse url = "http://127.0.0.1:5000" province = "山东" city = "青岛" note = "青岛地处山东半岛东南部沿海,胶东半岛东部,濒临黄海,隔海与朝鲜半岛相望,地处中日韩自贸区的前沿地带; 东北与烟台毗邻,西与潍坊相连,西南与日照接壤; 青岛因地理位置优越继而1891年清政府驻兵建置,1897年德国租借建设港口和铁路,青岛因“一港一路”而兴,拥有国际性海港和区域性枢纽航空港,是实施海上丝绸之路、履行国家一带一路战略重要的枢纽型城市。" # urllib.parse模块中的一个方法,用于将字符串进行URL编码,URL编码是将URL中的非ASCII字符和一些特殊字符转换成特定的格式 province = urllib.parse.quote(province) city = urllib.parse.quote(city) province = urllib.parse.quote(province) pc = "province=" + province + "&city=" + city + "¬e=" + note response = urllib.request.urlopen(url, data = pc.encode()) data = response.read() html = data.decode("utf-8") print(html)
post发送中文数据
server.py
import flask app = flask.Flask(__name__) @app.route('/', methods=['GET','POST']) def index(): try: province = flask.request.args.get('province') city = flask.request.args.get('city') note = flask.request.form.get('note') print(province) print(city) print(note) return province + "\n" + city + "\b" + note except Exception as e: print(e) debug = True if __name__ == '__main__': app.run()
client.py
import urllib.request import urllib.parse url = "http://127.0.0.1:5000" province = "山东" city = "青岛" note = "青岛地处山东半岛东南部沿海,胶东半岛东部,濒临黄海,隔海与朝鲜半岛相望,地处中日韩自贸区的前沿地带; 东北与烟台毗邻,西与潍坊相连,西南与日照接壤; 青岛因地理位置优越继而1891年清政府驻兵建置,1897年德国租借建设港口和铁路,青岛因“一港一路”而兴,拥有国际性海港和区域性枢纽航空港,是实施海上丝绸之路、履行国家一带一路战略重要的枢纽型城市。" # urllib.parse模块中的一个方法,用于将字符串进行URL编码,URL编码是将URL中的非ASCII字符和一些特殊字符转换成特定的格式 province = urllib.parse.quote(province) city = urllib.parse.quote(city) note = urllib.parse.quote(note) pc = "province=" + province + "&city=" + city n = "note=" + note response = urllib.request.urlopen(url+"?"+pc, data = n.encode()) data = response.read() html = data.decode() print(html)
Form表单中的POST
server.py
import flask app = flask.Flask(__name__) @app.route('/', methods=['GET','POST']) def index(): msg = "" user = flask.request.values.get('user', "") pwd = flask.request.values.get('pwd', "") if user=="123" and pwd=="123": msg = "登陆成功" elif user or pwd: msg = "登录失败" return flask.render_template("login.html", msg=msg) debug = True if __name__ == '__main__': app.run()
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form name = "form1" action="" method="post"> 用户<input type="text" name="user"><br> 密码<input type="password" name="pwd"><br> <input type="submit" value="登录"> </form> <div> {{msg}} </div> </body> </html>