4

I need to make a webpage for an assignment, it doesn't have to be uploaded to the web, I am just using a local .html file. I did some reading up and came up with the following html and python:

<!DOCTYPE html>
<html>
    <head>
        <title>
            CV - Rogier
        </title>
    </head
    <body>
        <h3>
            Study
        </h3>
        <p>
            At my study we learn Python.<br>
            This is a sall example:<br>
            <form action="/cgi-bin/cvpython.py" method="get">
                First Name: <input type="text" name="first_name">  <br />
                Last Name: <input type="text" name="last_name" />
                <input type="submit" value="Submit" />
            </form>
        </p>
    </body>
</html>

Python:

import cgi
import cgitb #found this but isn't used?

form = cgi.FieldStorage()

first_name = form.getvalue('first_name').capitalize()
last_name  = form.getvalue('last_name').capitalize()

print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Your name is {}. {} {}</h2>".format(last_name, first_name, last_name))
print ("</body>")
print ("</html>")

However this just gives the prints as text and not as a proper html file with the 1 line that I want.

Kai
  • 1,709
  • 1
  • 23
  • 36
RnRoger
  • 682
  • 1
  • 9
  • 33

4 Answers4

7

Do you have a web server like apache setup this is running on? If you don't I'm not sure this will work so you may want to have a look at Mamp To allow it to execute your python script you will also need to edit the httpd.conf file

From:

<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>

To:

  <Directory "/var/www/cgi-bin">
  Options +ExecCGI
  AddHandler cgi-script .cgi .py
  Order allow,vdeny
  Allow from all
  </Directory>

Alternatively

If you simply want to make an actual HTML file without setting up a server a very basic but crude way of doing this would be to simply write everything to a HTML file you create like:

fo.write("Content-type:text/html\r\n\r\n")
fo.write("<html>")
fo.write("<head>")
fo.write("<title>Hello - Second CGI Program</title>")
fo.write("</head>")
fo.write("<body>")
fo.write("<h2>Your name is {}. {} {}</h2>".format("last_name", "first_name", "last_name"))

fo.write("</body>")
fo.write("</html>")

fo.close()

Which will create a HTML document called yourfile.html in the same directory as your python project.

I don't recommend doing this, but I realise since it's an assignment you may not have the choice to use libraries. In case you, are a more elegant way would be to use something like yattag which will make it much more maintainable.

To copy the Hello World example from their website.

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('h1'):
    text('Hello world!')

print(doc.getvalue())

Update:

Another alternative if you don't have a local web server setup is to use Flask as your web server. You'll need to structure your project like:

    /yourapp  
    basic_example.py  
    /static/  
        /test.css
    /templates/  
        /test.html  

Python:

__author__ = 'kai'

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('test.html')

@app.route('/hello', methods=['POST'])
def hello():
    first_name = request.form['first_name']
    last_name = request.form['last_name']
    return 'Hello %s %s have fun learning python <br/> <a href="/">Back Home</a>' % (first_name, last_name)

if __name__ == '__main__':
    app.run(host = '0.0.0.0', port = 3000)

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="static/test.css">
        <title>
            CV - Rogier
        </title>
    </head>
    <body>
        <h3>
            Study
        </h3>
        <p>
            At my study we learn Python.<br>
            This is a sall example:<br>
            <form action="/hello" method="post">
                First Name: <input type="text" name="first_name">  <br />
                Last Name: <input type="text" name="last_name" />
                <input type="submit" name= "form" value="Submit" />
            </form>
        </p>
    </body>
</html>

CSS (If you want to style your form?)

p {
    font-family: verdana;
    font-size: 20px;
}
h2 {
    color: navy;
    margin-left: 20px;
    text-align: center;
}

Made a basic example based on your question here Hopefully this helps get you on the right track, good luck.

Kai
  • 1,709
  • 1
  • 23
  • 36
  • I don't know what I want, I just tried to make it work using this site https://www.tutorialspoint.com/python/python_cgi_programming.html How would I call/open that new html file from my main one? – RnRoger Apr 28 '17 at 11:32
  • 1
    Do you have the python script setup on a web server like apache? What is the aim? Do you just want to have python create a web page? – Kai Apr 28 '17 at 23:12
  • No, I need to make an html page, server is not required. I want to be able to enter a name (or anything) on the html page, have that sent to a python script, which does something with it, and relayed back to the browser (be it the same tab or a new tab) – RnRoger Apr 29 '17 at 14:39
  • 1
    (but I can use a web server if I want, and I'll try to with your answer) – RnRoger Apr 29 '17 at 14:46
0

Change the below in apache/conf/httpd.conf file:

<Directory "C:/xampp/cgi-bin"> 
    AllowOverride All
    Options None
    Require all granted
</Directory>

To:

  <Directory "C:/xampp/cgi-bin">
  Options ExecCGI
  AddHandler cgi-script .cgi .py
  Order allow,deny
  Allow from all
  </Directory>

otherwise run html form also using python script:(No need to change above http.conf file)

#!C:\Users\DELL\AppData\Local\Programs\Python\Python36\Python.exe

print("Content-type:text/html \r\n\r\n")
print('<html>')
print('<body>')
print('<form action="/cgi-bin/hello_get.py">')
print('First Name:<input type = "text" name = "first_name"><br/>')
print('Last Name:<input type = "text" name = "last_name" />')
print('<input type = "submit" value = "submit">')
print('</form>')
print('</body>')
print('</html>')`
Nani Chintha
  • 491
  • 5
  • 3
0

I'm new to both HTML and Python, but as far as I know HTML doesn't have to be indented. This means that you can pass a lot of HTML code in one python print. You can actually print a whole HTML code in one line.

I'm printing lists into html tables with for loops. The HTML code is not nice, but it's working. I guess you only need them to be temporary, as I do.

Cheers!

Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68
  • You're right that indentation doesn't matter in html. And that you can do it all in one line. But indentation or non-indentation of the html wasn't the problem. It was webserver setup (see the accepted answer). – Reinout van Rees Jul 08 '19 at 09:26
  • Sorry, I know, I just wanted to add it, because was a saw him writing it line by line, and that's painful to do. But I can't comment yet. – PlsDoNotWakeMeUp Jul 08 '19 at 11:11
  • A comment would be better, you're right. But not having enough points to comment yet is a very valid reason, of course :-) Welcome here at stackoverflow in any case! After a while, you'll have the points you need. – Reinout van Rees Jul 09 '19 at 00:52
0

firstly check browser url like that it looks like file:///C:/xampp/htdocs/cgi_python/form.html

that means your code is correct and no error but output show as a python script code because "code work in console not in browser"

i.e mean you directly open a file in htdocs folder and click filename.html and execute then output from in text format For open a browser

Solution is

  1. open browser type in url
  2. localhost/filepath eg. http://localhost/cgi_python/form.html then get the answer
slfan
  • 8,950
  • 115
  • 65
  • 78