专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

怎么用Python写一个网页程序_python

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/3/9 2:57:18       共计:3572 浏览

怎么用Python写一个网页程序?

直接上代码

1、服务器接口

import flask, os,sys,time

from flask import request, send_from_directory

interface_path = os.path.dirname(__file__)

sys.path.insert(0, interface_path) #将当前文件的父目录加入临时系统变量

server = flask.Flask(__name__)

#get方法:指定目录下载文件

@server.route('/download', methods=['get'])

def download():

fpath = request.values.get('path', '') #获取文件路径

fname = request.values.get('filename', '') #获取文件名

if fname.strip() and fpath.strip():

print(fname, fpath)

if os.path.isfile(os.path.join(fpath,fname)) and os.path.isdir(fpath):

return send_from_directory(fpath, fname, as_attachment=True) #返回要下载的文件内容给客户端

else:

return '{"msg":"参数不正确"}'

else:

return '{"msg":"请输入参数"}'

# get方法:查询当前路径下的所有文件

@server.route('/getfiles', methods=['get'])

def getfiles():

fpath = request.values.get('fpath', '') #获取用户输入的目录

print(fpath)

if os.path.isdir(fpath):

filelist = os.listdir(fpath)

files = [file for file in filelist if os.path.isfile(os.path.join(fpath, file))]

return '{"files":"%s"}' % files

# post方法:上传文件的

@server.route('/upload', methods=['post'])

def upload():

fname = request.files.get('file') #获取上传的文件

if fname:

t = time.strftime('%Y%m%d%H%M%S')

new_fname = r'upload/' + t + fname.filename

fname.save(new_fname) #保存文件到指定路径

return '{"code": "ok"}'

else:

return '{"msg": "请上传文件!"}'

server.run(port=8000, debug=True)

2、客户端请求

import requests

import os

#上传文件到服务器

file = {'file': open('hello.txt','rb')}

r = requests.post('http://127.0.0.1:8000/upload', files=file)

print(r.text)

#查询fpath下的所有文件

r1 = requests.get('http://127.0.0.1:8000/getfiles',data={'fpath': r'download/'})

print(r1.text)

#下载服务器download目录下的指定文件

r2 = requests.get('http://127.0.0.1:8000/download',data={'filename':'hello_upload.txt', 'path': r'upload/'})

file = r2.text #获取文件内容

basepath = os.path.join(os.path.dirname(__file__), r'download/')

with open(os.path.join(basepath, 'hello_download.txt'),'w',encoding='utf-8') as f: #保存文件

f.write(file)

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:你怎么看待人工智能的未来_python | ·下一条:python如何实现断言_python

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有