使用 WSGI 和 Apache 运行时 Python 的工作目录 [英] Python's working directory when running with WSGI and Apache

查看:29
本文介绍了使用 WSGI 和 Apache 运行时 Python 的工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 应用程序,它可以查询数据库并使用数据创建 Excel 电子表格.在将文件发送到客户端计算机之前,我需要将电子表格保存到服务器的磁盘.我正在使用 Flask 框架和 openpyxl 来生成电子表格.在 Flask 的开发服务器上运行时一切正常,但真正的服务器是带有 WSGI 的 Apache2.当我在那里运行它时,尝试保存电子表格时会引发权限被拒绝"错误.我不知道在 Apache/WSGI 中运行时 Python 的工作目录是什么.

I have a web application that, among other things, will query a database and create an Excel spreadsheet with the data. I need to save the spreadsheet to the server's disk before sending the file to the client machine. I'm using the Flask framework and openpyxl to generate the spreadsheet. Everything works fine when running on Flask's dev server, but the real server is Apache2 with WSGI. When I run it there, a "Permission Denied" error is raised when it tries to save the spreadsheet. I don't know what Python's working directory is when running in Apache/WSGI.

有没有办法,也许是在 WSGI 配置文件中,更改工作目录,或者以某种方式控制它将保存到的位置?如果可能,我想使用相对路径进行保存(它使代码更易于移植),这就是为什么更改工作目录是最好的解决方案.

Is there a way, maybe in the WSGI config file, to change the working directory, or somehow control where it will save to? If possible, I'd like to use relative paths for saving (it makes the code more portable) which is why changing the working directory is the best solution.

推荐答案

你不应该改变工作目录.

You should not change working directory.

使用:

import os
here = os.path.dirname(__file__)

变量here 将包含该代码文件所在的目录.然后,您可以为与之相关的事物构建绝对路径.

The variable here will then contain the directory where that code file is located. You can then construct absolute paths for things relative to that.

database = os.path.join(here, 'database.db')

请注意,在 Apache 中运行您的代码的用户仍然需要对该目录的读/写访问权限.

Do note that the user your code runs under in Apache still needs read/write access to that directory.

与往常一样,请务必阅读文档.文档的相关部分是:

As always, make sure you read the documentation. Relevant sections of documentation are:

这篇关于使用 WSGI 和 Apache 运行时 Python 的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆