0

I'm using Pycharm on Windows 10 and I'd like to use a html file inside a python file, so what should I do? I have my code already written, but the webpage seems not to run this html file.

To visualize this, I share my code:

from flask import Flask, render_template

app=Flask(__name__)

@app.route('/')
def home():
    return render_template("home.html")


@app.route('/about/')
def about():
    return render_template("about.html")

if __name__=="__main__":
    app.run(debug=True)

And after deploying this python file locally, I'd like these htmls to work, but the program doesn't seem to see them. Where should I put these html files or what should I do with them? I have them all in a one folder on my PC.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
chionae
  • 41
  • 1
  • 7
  • 2
    What do you mean by "use an html file inside a python file"? What do you mean by "run this html file"? An html file is text, so it's not clear how you would "run" a text document. What is "the webpage"? Are you running a web server? – Håken Lid May 15 '18 at 10:27
  • 1
    You can serve html files locally on `http://localhost:8000` by using `python -m http.server 8000` in the directory containing your html files. https://docs.python.org/3/library/http.server.html#module-http.server – Håken Lid May 15 '18 at 10:30
  • @HåkenLid I'm new here so I still don't know the terminology, but as you can see in the code above, I'd like to use html file inside a python file, but I don't know how to connect them. I was reading about templates (as you can see render_templates), but I still have no idea how to merge them inside Pycharm. – chionae May 19 '18 at 02:05
  • Do you get a `TemplateNotFound` exception, or any exception at all? https://stackoverflow.com/questions/23327293/flask-raises-templatenotfound-error-even-though-template-file-exists?noredirect=1&lq=1 – Håken Lid May 24 '18 at 12:56

1 Answers1

1

Use BeautifulSoup. Here's an example there a meta tag is inserted right after the title tag using insert_after():

from bs4 import BeautifulSoup as Soup

html = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div>test</div>
</html>
"""
soup = Soup(html)

title = soup.find('title')
meta = soup.new_tag('meta')
meta['content'] = "text/html; charset=UTF-8"
meta['http-equiv'] = "Content-Type"
title.insert_after(meta)

print soup

prints:

<html>
    <head>
        <title>Test Page</title>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    </head>
    <body>
        <div>test</div>
    </body>
</html>

You can also find head tag and use insert() with a specified position:

head = soup.find('head')
head.insert(1, meta)

Also see:

Neuron
  • 5,141
  • 5
  • 38
  • 59
PPL
  • 6,357
  • 1
  • 11
  • 30