如何访问我的Python应用运行下的localhost路径文件

0 投票
1 回答
28 浏览
提问于 2025-04-13 20:12

我在本地电脑(MacOS Ventura)上运行我的Python webapi应用,地址是localhost:5000。

我创建了一个名为“receivedfiles”的文件夹,里面放着myapp.py文件。我可以通过localshot:5000(或者用192.168.1.2代替localhost)访问我的应用,并通过我的webapi应用上传文件到receivedfiles文件夹。

这是我在webapi应用中用于文件上传的Python代码:

@app.route('/api/uploadfile', methods=['GET','POST'])
def uploadafile():
if 'myfile' not in request.files:
    return 'file could not be uploaded.', 400

myfile = request.files['myfile']
if myfile.filename == '':
    return 'please specify the filename', 400

# save the file to the receivedfiles folder
myfile.save('receivedfiles/' + myfile.filename)

return 'successfully uploaded', 200

这段代码运行得很好。

下面是相对目录结构:

.../myapp.py > my python webapi runs
.../receivedfiles/ > a directory for files
.../receivedfiles/sampleimage1.png > a file under that directory
192.168.1.2:5000/receivedfiles/ > relative path under localhost (192.168.1.2)
Users/myusername/myprojects/mypyhtonprojects/webapiproject1/receivedfiles/ is the absoulte (physical) path. I can access to the file via file:///Users/myusername/myprojects/mypyhtonprojects/webapiproject1/receivedfiles/sampleimage1.png on browser.

但是,当我尝试通过浏览器直接访问192.168.1.2:5000/receivedfiles/sampleimage1.png(我也试过不加端口号)或者在我的Flutter应用中访问时,返回了“未找到”的信息。

我该如何通过localhost(或者/receivedfiles路径及其下的文件)访问这些文件呢?

附注:我通过物理路径访问了这个文件夹,并且共享了任何访问权限。

谢谢任何帮助。

1 个回答

0

这个网页服务器并不能访问你项目中的所有文件。你需要把Flask整合进这个项目,指定哪些文件或文件夹是静态的,这样网页服务器才能访问它们。其实操作起来很简单,就像这样:

`

 from flask import Flask, send_from_directory

 app = Flask(__name__)

 # (your existing code) 

 @app.route('/uploads/<filename>')  #New route for serving uploads


 def uploaded_file(filename):

      return send_from_directory('receivedfiles', filename)

'

send_from_directory是Flask中的一个函数,用来从指定的文件夹中提供文件。新的路由 /uploads/ 让你可以访问像这样的文件: 192.168.1.2:5000/uploads/sampleimage1.png

撰写回答