Apache+Python环境下如何在服务器端保存网页生成的文件?
Permission Denied When Saving Dynamic Text File with Apache & mod_python
我在使用Apache和mod_python运行网页时,尝试保存动态生成的txt文件失败了。我的save函数代码如下:
def save(req): try: fe1=req.form['fe1'] fe2=req.form['fe2'] file=open("file.txt",'w') file.write("%s %s" %(fe1,fe2)) file.close() except KeyError: fe1='' fe2='' view=""" <!DOCTYPE html> <html> <head> </head> <body> <form method=post action="#"> <input type='text' id='fe1'></input> <input type='text' id='fe2'></input> <input type='submit'> </form> </body> </html> """.format(**locals()) return (view)
提交表单后出现了权限拒绝的错误,完整Traceback如下:
Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/mod_python/apache.py", line 399, in HandlerDispatch result = obj(req) File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 222, in handler published = publish_object(req, object) File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 446, in publish_object return publish_object(req, util.apply_fs_data(obj, req.form, req=req)) File "/usr/lib64/python2.7/site-packages/mod_python/util.py", line 642, in apply_fs_data return object(**args) File "<string>", line 5, in save IOError: [Errno 13] Permission denied: 'file.txt'
我需要解决这个权限问题,实现服务器端文件保存。
问题根源
这个错误的核心原因是Apache的运行进程没有权限写入你指定的文件路径。当你使用相对路径"file.txt"时,Python会尝试在Apache的当前工作目录(通常是/var/www/html、/var/www或httpd的安装目录)创建文件,但Apache的运行用户(比如apache、www-data或httpd,取决于你的系统)没有该目录的写入权限。
解决方案
1. 使用绝对路径并配置目录权限
首先,创建一个专门用于存储生成文件的目录,然后赋予Apache用户写入权限:
# 创建专属存储目录(路径可根据你的需求修改) sudo mkdir /var/www/server_stored_files # 将目录所有者改为Apache运行用户(这里以apache为例,部分系统是www-data) sudo chown apache:apache /var/www/server_stored_files # 设置安全的目录权限 sudo chmod 755 /var/www/server_stored_files
接着修改代码中的文件路径为绝对路径:
# 替换原来的open语句 file = open("/var/www/server_stored_files/file.txt", 'w')
2. 修复表单的隐藏问题
你的表单input标签只有id属性,没有name属性!req.form是通过name来获取表单值的,即使权限问题解决了,你依然会触发KeyError。给input加上name属性:
<input type='text' id='fe1' name='fe1'></input> <input type='text' id='fe2' name='fe2'></input>
3. 安全提示
- 不要把可写目录放在Web根目录(比如
/var/www/html)下,避免生成的文件被公开访问,带来安全风险。 - 如果必须放在Web根目录,记得在该目录下创建
.htaccess文件限制访问:
Order Deny,Allow Deny from all
按照以上步骤操作后,应该就能顺利解决权限问题,实现服务器端文件保存了。
内容的提问来源于stack exchange,提问作者e.jimenez
相关产品推荐
相关产品推荐

