python cgi PermissionError:[Errno 13]权限被拒绝:

python cgi PermissionError:[Errno 13]权限被拒绝:,python,apache,cgi,Python,Apache,Cgi,在我的macOS上,我尝试使用apache和python cgi构建一个非常简单的网站,在那里我可以上传一个图像,然后在成功或失败时输出。以下是index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> </head> <body> <

在我的macOS上,我尝试使用apache和python cgi构建一个非常简单的网站,在那里我可以上传一个图像,然后在成功或失败时输出。以下是index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>upload</title>
    </head>
<body>
<form enctype="multipart/form-data" action="/CGI-Executables/hello.py" method="post">
<p>upload:<input type="file" name="filename" /></p>
<p><input type="submit" value="upload" /> </p>
</form>
</body>
</html>


上传
上传:

下面是我编写python cgi部分的hello.py:

#!/anaconda3/bin/python
# -*- coding: UTF-8 -*-
print ('Content-Type: text/html')
print ('')
import cgi,os
import cgitb;cgitb.enable()
form=cgi.FieldStorage()
fileitem=form['filename']

if fileitem.filename:
    fn=os.path.basename(fileitem.filename)
    open('files/'+fn,'wb').write(fileitem.file.read())
    message = "successful"
else:
    message='fail'
    print ("""\
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,))

#/蟒蛇3/bin/python
#-*-编码:UTF-8-*-
打印('Content-Type:text/html')
打印(“”)
导入cgi,操作系统
进口cgib;cgib.enable()
form=cgi.FieldStorage()
fileitem=form['filename']
如果为fileitem.filename:
fn=os.path.basename(fileitem.filename)
打开('files/'+fn,'wb').write(fileitem.file.read())
message=“成功”
其他:
消息class='fail'
打印(“”)\
测试
%

“%”(消息,)
事实上,我从中复制了大部分代码,我还运行了chmod 755 hello.py来处理权限。但是,在我上传一个名为“123.png”的图像并单击上载按钮后,出现了一个错误:

Traceback (most recent call last):
  File "/Users/chuci/apa/CGI-Executables/hello.py", line 12, in <module>
    open('files/'+fn,'wb').write(fileitem.file.read())
PermissionError: [Errno 13] Permission denied: 'files/123.png'
回溯(最近一次呼叫最后一次):
文件“/Users/chuci/apa/CGI Executables/hello.py”,第12行,在
打开('files/'+fn,'wb').write(fileitem.file.read())
PermissionError:[Errno 13]权限被拒绝:“files/123.png”

我不知道为什么。事实上,我甚至不明白什么是“open('files/'+fn,'wb').write(fileitem.file.read())”用于。但如果我删除这一行,它将给我一个空白页。请给我一些建议,谢谢

您提到的这一行获取上传文件的内容,并使用web用户提供的原始文件名将其写入服务器目录

该错误与hello.py权限无关,为了修复该错误,您需要确保
文件
目录存在并且具有写入权限


但是,您很可能需要为上载的文件区域指定更准确的文件/目录名(例如,原始web用户文件名不是最好的主意),并添加适当的写入权限。

谢谢!我尝试使用一个更精确的目录,比如:open('/Users/chuci/apa/CGI Executables/files/'+fn,'wb')。write(fileitem.file.read())并运行:chmod 777/Users/chuci/apa/CGI Executables/files/来处理权限,但仍然存在相同的错误。噢,它现在可以工作了!但现在它只给了我一个空白页面,但应该有一个“成功”的输出。(如果我不上传任何文件并点击上传按钮,我可以得到一个“失败”的输出,这就是我所期望的)好的,现在它可以正确地输出我所期望的,不确定为什么它以前不能工作。。。谢谢!