Lesson 2 & 3

Python + HTML

+

http://vh7.uk/zd

?

Making a simple web server

Flask is what we will use to make a web server using Python.

  1. Go to https://tools.bartlweb.net/webssh/ and type in all of your credentials on the sheet given like shown --->
  2. Create a new folder: mkdir web
  3. Enter into the folder: cd web
  4. Make and edit a new file: touch firstwebsite.py
  5. Edit the file: nano firstsite.py
  6. Copy the code at the left
  7. Press CTRL-X then Y then ENTER to quit and save.
  8. Run the program: python3 firstsite.py
  9. Go to your domain: jake.malverncode.club

Challenge: Try and make a new page.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello!"

if __name__ == "__main__":
    app.run("0.0.0.0", 8091)

Leave this, just press enter

http://vh7.uk/zd

Serving HTML Files

  1. Make a new folder for HTML files: mkdir templates
  2. Enter into the HTML folder: cd templates
  3. Make a new HTML file: nano page.html
  4. Write some HTML
  5. Press CTRL-X then Y then ENTER to save and quit
  6. Go back to the previous folder: cd ../
  7. Edit your Python: nano firstsite.py
  8. Import render_template as well as Flask:                                                      
  9. Change the route to render the HTML:                                                                                                                                                                                      

Try and add some more pages and link them together.

from flask import Flask, render_template
@app.route("/")
def index():
    return render_template("page.html")

http://vh7.uk/zd

Dynamic Content

Now try updating your code to this: Try and work out what's happening. See if you can edit it.

server.py

templates/hello.html

from flask import Flask, render_template

app = Flask(__name__)

# ... other routes ...

@app.route("/hello/<name>")
def index():
    return render_template("hello.html", name=name)

if __name__ == "__main__":
    app.run("0.0.0.0", 8091)
<h1>Hello {{name}}!</h1>

http://vh7.uk/zd

Now go to {YOUR_NAME}.malverncode.club/hello/you

Challenge

Create a fully functioning website about you. Add links between different pages and ask for help if you thing of a good idea but don't know how you would do it.

That's a wrap!

Unfortunately, that's the end of the lesson. Save your work and just close the tab.

Next week we will either be continuing the work this week or using APIs.

Code Club: Python & HTML 2

By Jake Walker

Code Club: Python & HTML 2

  • 609