Im New In Flask . I'm try to make download list of /var/ directory files but
i can't find any way to make this link .
any file could be in this directory so tempfile could solve this problem .
i don't know the file so i can't copy file in flask directory ,
could any one tell me how can i make download link for file like this ?
I've never used flask, but have some experience with Django.
From quickly looking at the flask docs (rendering_templates) you would have to pass a context variable to the rendering function, then add it to the jinja template.
I would also suggest designating a different folder to place downloads, as giving users access to your /var/ folder can pose a security concern.
See below:
import os
from flask import Flask, render_template
app = Flask(__name__)
dloads_dir = '/var/www/mysite/downloads/'
dloads = os.listdir(dloads_dir).sort()
dloads_src = ['/downloads/{}'.format(i) for i in dloads]
#app.route('/Downloads')
def list_downloads():
return render_template('downloads.html', dloads=dloads, dloads_src=dloads_src)
Then in the html (should I say Jinja2) template:
<!doctype html>
<title>Hello from Flask</title>
{% for file in dloads %}
<a href="{{ dloads_src[loop.index0] }}" download>{{ file }}</a>
{% endfor %}
</html>
Here's where I found the loop.index method
(1) Edit: Fixed my bad html
Related
help needed for general advice with the example on how to implement django apps.
I am trying to implement django app called django-simple-polls.
After installing the app with...
pip install ...
...adding the app in INSTALLED APPS
...the server still runs...
...migrations runs with no problem...
...being able to create basic poll from the admin...
questions starts here as I do not know how can I see the poll on the server:
1)
urlpatterns = [
...
url(r'^poll/', include('poll.urls')),
]
I am guessing polls app is installed somewhere within django so I do not have to create any additional folder/file in my project. Do I need to import a library to use the include() function? It also mean I need to run polls only in that certain url? That means 'poll.urls' already exist?
2)
Add this tags in your template file to show the poll:
{% load poll_tags %}
...
{% poll %}`
Again my guess is just to create any template folder and put as base the code above. What does "..." mean?. Where do I put the above code? How do I call that HTML file?
Is that pretty much the only way of building apps into a project?
Thanks
ps. At the moment when visiting http://127.0.0.1:8000/poll
^poll/
^admin/
^news/index/ [name='index']
^news/post/ [name='view_post']
^news/view/category [name='view_category']
The current path, poll, didn't match any of these.
But there is path called poll. :)
Following the guidance: https://github.com/applecat/django-simple-poll/blob/master/README.md
I have created the following basic template:
<!DOCTYPE html>
<html>
<head>
<title>Polls</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
{% load poll_tags %}
...
{% poll %}
</body>
</html>
I am unable to render the surveys created in the admin onto the website.
questions starts here as I do not know how can I see the poll on the server
Answer: Make sure you change your URL mapping for your poll's urls.py.
urlpatterns = [ ... url(r'^poll/', include('poll.urls')), ]
This should be added to your project's urls.py
Again my guess is just to create any template folder and put as base the code above. What does "..." mean?. Where do I put the above code? How do I call that HTML file?
If you've set your templates folder in your settings.py you can create another folder named poll then you put your templates there. Then on your views you do.
from django.shortcuts import render
def index(request):
return render(request, 'poll/yourtemplatename.html')
I tried to read file print.html that located in path: templates/print.html.
So, I used url_for() to refer to it as below:
{{ url_for('templates', filename='print.html') }}
However, I got an error as below Traceback:
BuildError: ('templates', {'filename': 'print.html'}, None)
What's wrong with this?
If I used {{ url_for('static', filename='print.html') }}, it just working find. However, file that I tried to read is not in static folder, it was in templates/print.html instead.
How can I use url_for() to read my file print.html in templates folder? Thanks.
I'll start by saying-- if you're trying to url_for a template, it's likely you're misunderstanding a concept. But, assuming you're know the difference between a rendered template and a static asset:
You could build a route for the print.html:
#app.route('/print')
def print():
return render_template('print.html')
Which would then enable you to url_for('print') to get the resolved url, and any dynamic components in your print.html template would get rendered to static html.
Otherwise, if the print.html is truly static-- just move it to the static folder, and use the url_for('static', filename='print.html') as you've indicated.
There's a handy Flask blueprint pattern that's useful if you're just rendering off a bunch of templates and don't need any view logic, see it here
I have a flask application where a user's profile image is stored. I originally stored the images in the static directory like so:
application.py
templates/
static/userdata/user/icon.png
Though I don't think this is a good idea because it is not good practice to modify the static directory in production.
I tried making a new userdata folder at root like so:
application.py
templates/
static/
userdata/user/icon.png
Though when I try to access the file with Jinja and HTML,
<img src="/userdata/user/icon.png">
the image does not show. Why is this?
Thanks, in advance.
Use the url_for function
.html
<img src="{{ url_for('userdata', filename='/user/icon.png')}}">
.py
from flask import send_file
#route('/userdata/<filename:filename>')
def get_user_data_files(filename):
return send_file(app.config['USER_DATA_FOLDER'] + filename)
I'm using Flask with Flask-FlatPages and I'm trying to get a list of all the subdirectories in the Flatpages /pages folder. These folders should appear as a link that when clicked append the foldername on the url. In the pages folder are two subdirectories: misc and test. I have tried this:
#app.route('/list')
def listdir():
folders = os.listdir('./pages')
return render_template('list.html', folders=folders)
and the template is using this part:
<ul class="unstyled">
{% for folder in folders %}
<li>
<h3>{{ folder }}</h3>
</li>
....
but it just gives me an empty page.
i have tried a bit and now it gives me at least an error:
BuildError: ('folder', {'name': 'test'}, None)
With this BuildError, Flask is telling you that it can not find the URL for a view named "folder" that takes a single "name" parameter. Do you have such a view? Please provide all of your views’ code.
You need to alternate single and double quotes in your template use; instead of "{{ url_for("folder", name=folder) }}" you need '{{ url_for("folder", name=folder) }}'.
While testing and developing your application, add debug=True to your run statement. This adds error pages with very nice debugging tools: app.run(host='0.0.0.0', port=10000, debug=True)
I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_name))
output = template.render(template_file,template_values)
self.response.out.write(output)
For my current app, I want to render a template contained in a
string. I'm using the following code:
t = template.Template(template_string)
c = template.Context(template_values)
output = t.render(c)
self.response.out.write(output)
It renders the template, but not the "include" tags contained within
the string. For example, the string template
"hello world {% include 'helloworld.html' %}"
renders "hello world" but does not render the contents of
'helloworld.html'.
I'm guessing that this has something to do with the string not being
in the same directory as 'helloworld.html', but I'm not sure how to
specify that the include tags should look in '/templates/*'
Any help would be appreciated,
Arjun
The webapp framework uses Django 0.9.6 templates. If you're loading templates from a string as you describe above, you need to configure the template loader so it can find dependencies loaded from files. Here's how webapp configures them.
{% include 'dirname/helloworld.html' %}
should work!