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.

4
  • 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? Commented May 15, 2018 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. docs.python.org/3/library/http.server.html#module-http.server Commented May 15, 2018 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. Commented May 19, 2018 at 2:05
  • Do you get a TemplateNotFound exception, or any exception at all? stackoverflow.com/questions/23327293/… Commented May 24, 2018 at 12:56

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.