python cgi编程学习笔记(一)

文章目录

      • python cgi编程学习笔记(一)
        • 1.简单的上传文件

python cgi编程学习笔记(一)

1.简单的上传文件

这是网页代码

print ("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)title>
head>
<body>
   <p>%sp>
body>
html>
""" % (message,))

这是Python代码

#!C:\Users\m1767\AppData\Local\Programs\Python\Python38\python.exe
#-*- coding:UTF-8 -*-
# 引入 CGI 处理模块 
import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()
fileitem = form['filename']
if fileitem.filename :
    fn = os.path.basename(fileitem.filename)
    if os.path.isfile(fn):
        pass
    else:
        open('./tem/'+fn,'wb').write(fileitem.file.read())
    message = '文件'+fn+'上传成功'
else:
    message = "没有文件上传"

print ("""\
Content-Type: text/html\n


菜鸟教程(runoob.com)


   

%s

"""
% (message,))

这是我自己写的代码,之前使用菜鸟编程的代码发现行不通,后来查了下,是由于文件储存路径有问题,于是我这么改了一下,菜鸟教程里的代码如下:

#!/usr/bin/python3

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# 获取文件名
fileitem = form['filename']

# 检测文件是否上传
if fileitem.filename:
   # 设置文件路径 
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())

   message = '文件 "' + fn + '" 上传成功'
   
else:
   message = '文件没有上传'
   
print ("""\
Content-Type: text/html\n



菜鸟教程(runoob.com)


   

%s

"""
% (message,))

查看错误logs,发现错误原因是这样的Response header name '

你可能感兴趣的:(Python)