for file in request.files.getlist('files'): filename = file.filename file.save(os.path.join(folder_name, filename))
时间: 2023-12-13 09:05:09 浏览: 142
这段代码是用来处理上传文件的。首先通过`request.files.getlist('files')`获取上传的文件列表,然后遍历列表中的每个文件,获取文件名并保存到指定的文件夹中。具体实现是通过调用`file.save()`方法来实现的,该方法需要传入文件保存的路径。在这个例子中,路径是通过`os.path.join()`方法来构建的,它将文件名和文件夹名拼接起来,形成完整的文件路径。
相关问题
@app.route('/restruct', methods=['POST']) def restruct(): dch = request.form['dch'] dch_folder = "restr" + dch count = 1 while os.path.exists(os.path.join('D:\cj', dch_folder)): dch_folder = "restr" + dch + "_" + str(count) count += 1 os.makedirs(os.path.join('D:\cj', dch_folder, 'photos')) os.makedirs(os.path.join('D:\cj', dch_folder, 'kmls')) os.makedirs(os.path.join('D:\cj', dch_folder, 'project')) photos_folder = os.path.join('D:\cj', dch_folder, 'photos') kmls_folder = os.path.join('D:\cj', dch_folder, 'kmls') project_folder = os.path.join('D:\cj', dch_folder, 'project') for file in request.files.getlist('files'): filename = file.filename file.save(os.path.join(photos_folder, filename)) dhs = request.form.getlist('dh') for dh in dhs: src_path = os.path.join(r'D:/911kml/', dh + '.xlsx.kml') dst_path = os.path.join(r'D:/cj', dch_folder, 'kmls/', dh + '.xlsx.kml') shutil.copy(src_path, dst_path) subprocess.Popen(["python", "restruct.py", dch, photos_folder, project_folder, kmls_folder])使用python3.6版本的websocket,将这段代码运行中的输出信息,实时发送给前端,给出server.py和client.py
server.py:
```python
import asyncio
import websockets
import subprocess
async def echo(websocket, path):
dch = await websocket.recv()
dch_folder = "restr" + dch
count = 1
while os.path.exists(os.path.join('D:\cj', dch_folder)):
dch_folder = "restr" + dch + "_" + str(count)
count += 1
os.makedirs(os.path.join('D:\cj', dch_folder, 'photos'))
os.makedirs(os.path.join('D:\cj', dch_folder, 'kmls'))
os.makedirs(os.path.join('D:\cj', dch_folder, 'project'))
photos_folder = os.path.join('D:\cj', dch_folder, 'photos')
kmls_folder = os.path.join('D:\cj', dch_folder, 'kmls')
project_folder = os.path.join('D:\cj', dch_folder, 'project')
async for file in websocket:
filename = file.filename
file.save(os.path.join(photos_folder, filename))
dh = await websocket.recv()
src_path = os.path.join(r'D:/911kml/', dh + '.xlsx.kml')
dst_path = os.path.join(r'D:/cj', dch_folder, 'kmls/', dh + '.xlsx.kml')
shutil.copy(src_path, dst_path)
process = await asyncio.create_subprocess_exec(
"python", "restruct.py", dch, photos_folder, project_folder, kmls_folder,
stdout=asyncio.subprocess.PIPE
)
while True:
output = await process.stdout.readline()
if output == b'':
break
await websocket.send(output.decode())
async def main():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
```
client.py:
```python
import asyncio
import websockets
import aiohttp
async def upload_files(dch, files, dh):
async with aiohttp.ClientSession() as session:
async with session.ws_connect('ws://localhost:8765') as ws:
await ws.send(dch)
for file in files:
await ws.send(file)
await ws.send(dh)
async for message in ws:
print(message)
async def main():
dch = 'example'
files = ['example1.jpg', 'example2.jpg']
dh = 'example'
await upload_files(dch, files, dh)
if __name__ == "__main__":
asyncio.run(main())
```
@app.route('/tiji', methods=['POST']) def tiji(): dch = request.form.get('dch') name = request.form.get('filename') print(name) folder_name = f"{dch}dianyun" if not os.path.exists(folder_name): os.mkdir(folder_name) for file in request.files.getlist('file'): filename = file.filename file.save(os.path.join(folder_name, filename)) dhs = request.form.getlist('dh') print(len(dhs)) for i in range(len(dhs)): print(dhs[i]) folder_path = os.path.join(folder_name) file_name = f"{name}.laz" if has_file(folder_path, file_name): else: return jsonify({"code": 200, "msg": "no_file"}) return jsonify({"code": 200, "msg": "done"}) 这段代码if下面写什么可以发送给前端消息,然后继续运行,最后执行return
如果你想在 `if` 分支中发送消息给前端后继续运行,你可以使用 SocketIO 的 `emit` 方法,并将 `broadcast=True` 作为参数传递给它,这样可以使消息发送给所有连接的客户端,而不仅仅是当前请求的客户端。然后,你可以在 `if` 分支外部执行其他代码,并在最后执行 `return` 返回最终的响应。
下面是修改后的代码示例:
```python
from flask import Flask, request, jsonify
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/tiji', methods=['POST'])
def tiji():
dch = request.form.get('dch')
name = request.form.get('filename')
print(name)
folder_name = f"{dch}dianyun"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
for file in request.files.getlist('file'):
filename = file.filename
file.save(os.path.join(folder_name, filename))
dhs = request.form.getlist('dh')
print(len(dhs))
for i in range(len(dhs)):
print(dhs[i])
folder_path = os.path.join(folder_name)
file_name = f"{name}.laz"
if has_file(folder_path, file_name):
socketio.emit('output', {"code": 200, "msg": "success"}, broadcast=True) # 发送消息给前端
else:
return jsonify({"code": 200, "msg": "no_file"})
# 在这里执行其他代码逻辑
return jsonify({"code": 200, "msg": "done"})
if __name__ == '__main__':
socketio.run(app)
```
在上述代码中,我们在 `if` 分支中使用 `socketio.emit` 方法发送消息给前端,并将 `broadcast=True` 作为参数传递给它,以确保消息发送给所有连接的客户端。然后,在 `if` 分支外部,你可以执行其他代码逻辑。最后,使用 `return` 返回最终的响应。
请确保已正确安装 Flask-SocketIO 扩展,并在启动应用程序时使用 `socketio.run(app)`。
希望这次能解决你的问题!如果还有其他疑问,请随时提问。
阅读全文