0
#!/usr/bin/python3

import cgi
import cgitb
import urllib.request
import os
import sys

def enco_print(string="", encoding = "utf8"):
    sys.stdout.buffer.write(string.encode(encoding) + b"\n")

cgitb.enable()


form = cgi.FieldStorage(endcoding="utf8")

name_name= form.getvalue("name")
url_name = form.getvalue("url")


response = urllib.request.urlopen(str(url_name)) 
html = response.read().decode("utf8")

if not os.path.exists("gecrwalt"):
    os.mkdir("gecrwalt")      


with open("/gecrwalt/" + str(url_name) + ".html", "w", endcoding="utf8")
as f:
f.write(str(html))

When I try to run this script, I get 500 Status Error on my Website. I can´t see what´s wrong with this code.

I´m very thankful for help.

idjaw
  • 25,487
  • 7
  • 64
  • 83

1 Answers1

0

There are a few typos where you wrote endcoding instead of encoding.

The last segment here

with open("/gecrwalt/" + str(url_name) + ".html", "w", endcoding="utf8")
as f:
f.write(str(html))

has broken indentation, not sure if this was due to a copy-paste error here on Stackoverflow.

Another issue here is that (if I understood your code correlty) url_name will contain a complete URL like http://example.com, which will result in an error because that filename is invalid. You will have to come up with some schema to safely store these files, urlencode the URL or take a hash of the URL. Your save path also starts with /, not sure if intentational, starts at the file system root.

Changing the typo and the last bit has worked for me in a quick test:

with open("gecrwalt/something.html", "w", endcoding="utf8") as f:
    f.write(str(html))

Debugging hint: I started a local Python webserver process with this command (from here)

python3 -m http.server --bind localhost --cgi 8000

Accessing http://localhost:8000/cgi-bin/filename.py will show you all errors that occur, not sure about the webserver you are currently using (there should be error logs somewhere I guess).

chrki
  • 6,143
  • 6
  • 35
  • 55
  • chrki at first: thank you very much. You helped me a lot and I didn´t see the mistakes. After I changed these typos and mistakes, I get now Status Error 405. Do you know why? :-) – user8067545 Jun 24 '17 at 17:39
  • @user8067545 Are you able to execute the script like this? `http://localhost:8000/cgi-bin/filename.py?name=test&url=http%3A%2F%2Fexample.com` -- 405 means "Method not allowed", I'm guessing here: if you have a `
    ` somewhere change `method="POST"` to `method="GET"`... might be stuff for a separate question though
    – chrki Jun 25 '17 at 15:54