Can't show html using Flask - python

So I have been trying to get used to Flash in python but I've come across a problem. I want that when http://localhost:5000/ is inserted in the browser a html page is displayed. I've tried multiple ways to do this like using the render_template() but that returns me a jinja2.exceptions.TemplateNotFound: index.html. I've also tried a simple return redirect() but that throws something saying the adress was not recognized or understood. When I tried using the url_for() it threw 404 - not found. I really have no idea how to fix this.
# htppserver.py
import flask
import threading
app = Flask(__name__, template_folder="Dashboard/website")
#app.route("/site", methods=["GET"])
#app.route("/", methods=["GET"])
def get_site():
return render_template("index.html")
x = threading.Thread(target=app.run)
x.start()
Currently my dir system looks something like this
main_folder # This is the working directory accordingly to os.getcwd()
├──cogs
│ └──httpserver.py # Source code is here
└──Dashboard
└website
├──...
├──index.html # This is the file I want to show
└──...
Thanks

put your html files in a folder called "templates" in the same directory as the python file that serves

Related

Having trouble with Flask in python, either says render_template doesn't exist, or that my template doesn't exist

I am doing an assignment to integrate a python script with HTML templates, and while the IDE is giving me no errors, when I try to actually run the website it gives me an "internal server error" and in the debug menu it says either that it doesn't recognize the Flask command "render_template" or doesn't recognize the HTML file it's supposed to render. The HTML file is stored both in the same folder as the python file and a copy is stored in a seperate "templates" folder located in the same folder as the python file. I really have no idea what's going on, the teacher has been no help.
I tried renaming the files, spell checked the imports repeated, checked all the commands, made copies of the python and Html files to see if the directorry was the problem. I really am not sure what else to try
...from flask import Flask
...from flask import render_template
...from flask import request
...from flask import flash
...import datetime
...app = Flask(__name__)
```#app.route('/')
...#the home page
...def home():
... return render_template('home_page.html')
```#app.route('/clock/')
...#the clock site
...def time_site():
... return date_and_time()
...def date_and_time():
... cur_time = str(datetime.now())
...return render_template('clock.html', cur_time)
```if __name__ == "__main__":
...app.run()

Flask-Uploads URL is always a 404

I'm using Flask-Uploads to upload a file and output the URL. However, for some reason the URL always points to a 404! I can see the file in the correct folder, but the URL seems to not be able to find it. Here are the configurations I'm using...
UPLOADS_DEFAULT_URL = os.environ.get("UPLOADS_URL", "http://localhost:5000/")
UPLOADS_DEFAULT_DEST = "app/uploads"
I also have an Upload set defined as:
productUploadSet = UploadSet('plist', extensions=('xlsx', 'csv', 'xls'))
The file is found in "app/uploads/plist/filename.csv" and I'll get a url returned to me like "http://localhost:5000/productlist/filename.csv" but whenever I open the URL it is always a 404. I know that the url method from Flask-Uploads doesn't actually check fi the file exists, but I can see the file is actually there. Is it looking in the wrong place somehow? Thanks for any help.
From Flask's guide to uploading files:
Now one last thing is missing: the serving of the uploaded files. As of Flask 0.5 we can use a function that does that for us:
from flask import send_from_directory
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
Alternatively you can register uploaded_file as build_only rule and use the SharedDataMiddleware. This also works with older versions of Flask:
from werkzeug import SharedDataMiddleware
app.add_url_rule('/uploads/<filename>', 'uploaded_file',
build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/uploads': app.config['UPLOAD_FOLDER']
})
Without implementing one of these, Flask has no idea how to serve the uploaded files.

Flask: How to serve static html?

I am trying to serve a static html file, but returns a 500 error
(a copy of editor.html is on .py and templates directory)
This is all I have tried:
from flask import Flask
app = Flask(__name__, static_url_path='/templates')
#app.route('/')
def hello_world():
#return 'Hello World1!' #this works correctly!
#return render_template('editor.html')
#return render_template('/editor.html')
#return render_template(url_for('templates', filename='editor.html'))
#return app.send_static_file('editor.html') #404 error (Not Found)
return send_from_directory('templates', 'editor.html')
This is the response:
Title: 500 Internal Server Srror
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Reducing this to the simplest method that'll work:
Put static assets into your static subfolder.
Leave Flask set to the default, don't give it a static_url_path either.
Access static content over the pre-configured /static/ to verify the file works
If you then still want to reuse a static file, use current_app.send_static_file(), and do not use leading / slashes:
from flask import Flask, current_app
app = Flask(__name__)
#app.route('/')
def hello_world():
return current_app.send_static_file('editor.html')
This looks for the file editor.html directly inside the static folder.
This presumes that you saved the above file in a folder that has a static subfolder with a file editor.html inside that subfolder.
Some further notes:
static_url_path changes the URL static files are available at, not the location on the filesystem used to load the data from.
render_template() assumes your file is a Jinja2 template; if it is really just a static file then that is overkill and can lead to errors if there is actual executable syntax in that file that has errors or is missing context.
All the answers are good but what worked well for me is just using the simple function send_file from Flask. This works well when you just need to send an html file as response when host:port/ApiName will show the output of the file in browser
#app.route('/ApiName')
def ApiFunc():
try:
#return send_file('relAdmin/login.html')
return send_file('some-other-directory-than-root/your-file.extension')
except Exception as e:
logging.info(e.args[0])```
send_from_directory and send_file need to be imported from flask.
Your code sample would work if you do the following:
from flask import Flask, send_from_directory
app = Flask(__name__, static_url_path='/templates')
#app.route('/')
def hello_world():
return send_from_directory('templates', 'editor.html')
However, remember if this file loads other files e.g. javascript, css, etc. you would have to define routes for them too.
Also, as far as I understand, this is not the recommended method on production because it's slow.

Web.py How to access render function in this case

I am new to Python and Web.py, but I am tearing my hair out over this issue. I have a code layout where I have my app.py file in the root of my site. All the pages are in a sub director, named pages. Here is my app.py code
import web
import page.index
urls = (
'/', 'page.index.index',
)
render = web.template.render('templates/', base = "layout") # Start the template
app = web.application(urls, globals()) # Start the app
if __name__ == "__main__":
app.run()
Now, it executes perfectly. Now, in the index.py file, this is my code:
class index:
def GET(self):
testing = 'Hello World'
return render.index(testing)
The error I am getting is this:
<type 'exceptions.NameError'> at /
global name 'render' is not defined
Python /Volumes/Local Disk 2/Work/Casting Board/com/index.py in GET, line 3
Web GET http://127.0.0.1:8080/
Basically, I am trying to access the function ( or it is method or class. Just coming from PHP so don't know the terminally) render from a moucle called page.index. How can I get around this?
In the index.py page, should you include from web.template import render ?
Presuming web.template.render() returns an object containing an index() method (I'm not familiar with web.py), you'll need to tell Python where to find this object.
In index.py:
import app
Then:
return app.render.index(testing)
You can just include you index class (index.py) within your app.py file. Importing the web module then will bring in the definition of the function "render" at the beginning of your code.

web.py / pythonpath confusion

Im playing around with web.py as a lightweight web framework. Im having problems when i attempt to move the actual implementation of my page into a separate file instead of the root file. As a demonstration, My core.py file looks like this:
import web, sys, os
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
urls = (
'/', 'index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
if __name__ == "__main__":
app.run()
ive moved my implementation into a file called index.py at the same level as core.py. My implementation looks like this:
class index:
def GET(self):
return "Hello world"
however, whenever i run my application, i get an error:
<type 'exceptions.KeyError'> at /
can anybody tell me what is going on?
According to http://webpy.org/tutorial3.en#urlhandling, web.py does a lookup for the classes you specified in your urls in the global namespace.
In your core.py there is no class named index (after you moved it), that's what causes this keyerror. In my test I could fix that by importing the index class in core.py.
from index import index
(I haven't used web.py before, so please correct me if I'm wrong)
You can add dots to crawl into modules. So say you have a folder controllers with a file named file.py and you wanted to access the controller named index:
from controllers import *
urls = (
'/', 'controllers.file.index'
)
I'm guessing the bug is in your template. I hit this error when if forgot a ':' on an if statement in my template.

Categories