回答編集履歴

1

pythonの言語バージョンによる違いを追記

2017/10/01 03:39

投稿

dodox86
dodox86

スコア9183

test CHANGED
@@ -48,7 +48,7 @@
48
48
 
49
49
 
50
50
 
51
- ```python
51
+ ```python2
52
52
 
53
53
  #!/usr/bin/env python
54
54
 
@@ -121,3 +121,99 @@
121
121
 
122
122
 
123
123
  ```
124
+
125
+ ###python3に関して追記
126
+
127
+ python3 でのご質問だったのかもしれませんので、すみませんが以下、追記させていただきます。
128
+
129
+
130
+
131
+ 参考にされたサイト様のサンプルプロはpython2 のものです。
132
+
133
+ 私が提示したコードもpython2 のものなので、サーバー上でpython3でcgiを
134
+
135
+ 稼動させる場合、文法エラーで動作しません。
136
+
137
+ コードをpython3でほぼ等価なものに書き直し、動作確認したものを以下に示します。
138
+
139
+ ※「アップロード」の部分はそのままだとエラーになり、
140
+
141
+ コードが煩雑になるのでASCII文字列に直させてもらいました。
142
+
143
+
144
+
145
+ 今後pythonでcgiを造られる場合は、バージョンの違いに注意する必要があるかとは思います。
146
+
147
+
148
+
149
+ ```python3
150
+
151
+ #!/usr/bin/python3
152
+
153
+ # -*- coding: utf-8 -*-
154
+
155
+ import cgi
156
+
157
+ import os, sys
158
+
159
+
160
+
161
+ try:
162
+
163
+ import msvcrt
164
+
165
+ msvcrt.setmode(0, os.O_BINARY)
166
+
167
+ msvcrt.setmode(1, os.O_BINARY)
168
+
169
+ except ImportError:
170
+
171
+ pass
172
+
173
+
174
+
175
+ result = 'DUMMY'
176
+
177
+ form = cgi.FieldStorage()
178
+
179
+ #if form.has_key('file'):
180
+
181
+ if 'file' in form:
182
+
183
+ item = form['file']
184
+
185
+ if item.file:
186
+
187
+ # fout = file(os.path.join('/tmp', item.filename), 'wb')
188
+
189
+ fout = open(os.path.join('/tmp', item.filename), 'wb')
190
+
191
+ while True:
192
+
193
+ chunk = item.file.read(1000000)
194
+
195
+ if not chunk:
196
+
197
+ break
198
+
199
+
200
+
201
+ fout.write(chunk)
202
+
203
+ fout.close()
204
+
205
+ result = 'upload is done'
206
+
207
+ #result = "アップロード"
208
+
209
+
210
+
211
+ print("Content-Type: text/html")
212
+
213
+ print("")
214
+
215
+ html = "<html><body>{0}</body><html>"
216
+
217
+ print(html.format(result))
218
+
219
+ ```