flask how to pass variable to url for different domain - python

I've built a Flask app, and I'm trying to figure out how to pass a variable into a link that is not hosted by me. Concretely, it's a completely different website that I have no control over.
I've tried
Link
However this did not capture the {{ variable}} , and in fact just resulted in domain.com.
I've looked into url_for but that only seems to work when its for your own website? I think?
e.g. localhost. This particular link prefix is for a completely different domain and host.
Any help appreciated. Thank you!

You need to pass the variable variable to your render template.
Eg:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html", variable="whatever")
if __name__ == "__main__":
app.run(debug=True)
Then in index.html:
<html>
<head>
<title>Your title</title>
</head>
<body>
Link <!-- This will go to http://domainname.org/whatever -->
</body>
</html>

Related

CSS not loading completely when i run my python application

I intend to apply basic CSS over my HTML under my python/ flask application. I got a HTML with CSS file from getbootstrap.com.
Link: https://getbootstrap.com/docs/5.2/examples/cover/
The HTML loads up completely when I run it locally (outside the project) but it does not load properly when I try running the application using flask on dev (localhost).
Can someone please suggest a fix here. I have tried placing the CSS file in static folder and then loading it with below approach (adding link to CSS file in my HTML):
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheets/cover.css') }}">
My project directory looks like:
env
static > stylesheets > cover.css
templates > index.html
app.py
app.py file:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def base():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, port=5000)
By default it comes with the following link:
<link href="cover.css" rel="stylesheet">
After running the project, it looks like as attached under the snap. This means that the CSS is getting applied but not completely.

why I do get a broken picture icon instead of the image in my folder when I run the flask app? [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 11 months ago.
I get this broken-image-icon thing when I run my flask app
from flask import Flask
panda = Flask(__name__)
#panda.route("/")
def home():
return '''
<body>
<img src="panda.jpg"
alt="A picture of a panda"
height="600" width="600">
</body>
'''
if __name__ == "__main__":
panda.run()
When I set the source of the <img tag to the relative or absolute path of that image (it is in the same directory as the flask app btw) the server doesn't show the image. Amazingly, when I set the source as the url of that image (it is taken from the internet) it works just fine!
Could this be a problem specific to my device or maybe the web servers I use? I use Google Chrome and Microsoft Edge, same problem on both. Is it a flask thing? because the same html code works perfectly fine on its own, it is only within flask that I get this problem.
I need help, please don't answer with "just use the url then!", obviously I want to upload different images and this is just a simplified version of my actual code, this is the problem part of it, everything else is ok.
you need to use flask render templates.
File structure:
app.py
static
|----test.jpg
templates
|----index.html
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
app.run()
index.html
<html>
<head>
</head>
<body>
<h1>Index page</h1>
<img src="{{url_for('static', filename='test.jpg')}}" />
</body>
</html>

Structuring my flask application in self contained folders

I have an app i am making and i would like to hold all python code, css and js assets inside a folder and name it appropriately so that one person can do a complete module,test it and upload it to the main project.
I am planning to have something like this structure
index.py
global_assets
global_classes
global_html_components
home(assets(js,css,images),home.html,home_widget_1.html,home_widget_2.html,home_widget_3.html,controller.py,model.py)
services
products
dashboard
I have this script.py
from flask import *
app = Flask(__name__)
#app.route('/user/<uname>')
def message(uname):
return render_template('message.html',name=uname)
if __name__ == '__main__':
app.run(debug = True)
and message.html
<html>
<head>
<title>Message</title>
</head>
<body>
<h1>hi, {{ name }}</h1>
</body>
</html>
I want my app to have one entry at index.py such that i can visit urls of any of my modules and the page displays for instance in the code above
http://localhost:5000/home/user/admin where home is one of the folders i named above.
Is this kind of structure possible in flask?

Custom static path in flask api?

I have referred the link here: More than one static path in local Flask instance and tried getting to display the image files in the browser tab, but couldn't do so. Unable to make out the mistake.
stored_name is the physical filename of the file stored in the path specified by the app config constant variable: 'UPLOAD_FOLDER'. This folder is NOT in the static folder and its sub-folder path. I would like to increase storage capacity of files (maybe image files also), later by adding harddisk space, which is difficult if I use the static folder for storage. I don't want to override the static folder during app initialisation(which works)
Code snippets:
from flask import send_from_directory
#app.route('/api/v1.0/docs/<path:filename>', methods=["GET"])
def img_render(filename):
print 'Called here'
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"])
def image_rendering(doc_id):
s = select([docs]).where(docs.c.id==doc_id)
rs = conn.execute(s).fetchone()
filename = str(rs[docs.c.stored_name])
return url_for('img_render', filename=filename)
Html template:
<!DOCTYPE html>
<html>
<body>
<img src="{{url_for('img_render', filename=filename) }}" />
</body>
</html>
The template is in the templates folder itself. If I override the original static folder during init of the application, I am able to get the images displayed in the browser, but I have to change my reference to the static folder for the application OR I will have to upload images into the static folder from the application, which I don't want to do. What is the mistake that it just displays the path of the image in the browser example:
/api/v1.0/docs/1_20160707_121214.jpg
and not the image itself? Where is the mistake in the code? Using flask v .0.11, linux 2.7.
Your image_rendering method is returning a string (which is what you see in the browser) when it should be returning the result of a template rendering.
Replace 'mytemplate.html' with the name of your html template in the following sample.
from flask import render_template
#app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"])
def image_rendering(doc_id):
s = select([docs]).where(docs.c.id==doc_id)
rs = conn.execute(s).fetchone()
filename = str(rs[docs.c.stored_name])
return render_template('mytemplate.html', filename=filename)
Here is a simple Flask App that works in Windows. In my d:\temp folder there is a file test.jpg. Make sure your Flask App has the correct permissions to read the files in the upload folder. To use browse to http://127.0.0.1:5000/api/v1.0/docs/99:
from flask import Flask, send_from_directory, render_template
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'd:/temp'
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/api/v1.0/docs/<path:filename>', methods=["GET"])
def img_render(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename=filename, mimetype='image/jpeg')
#app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"])
def image_rendering(doc_id):
# ignore doc_id, we'll use a constant filename
filename = 'test.jpg'
return render_template('test.html', filename=filename)
if __name__ == '__main__':
app.run()
test.html in the templates folder:
<!DOCTYPE html>
<html>
<body>
<img src="{{url_for('img_render', filename=filename) }}" />
</body>
</html>

Python Not Finding CSS File

Hi I'm new to using python with web programs and I'm trying to make a basic website that uses a CSS style sheet. I have three files: app.py, index.html, and style.css. They are all in the same directory. When I run app.py and go to localhost:8080, it displays "Hello World!", but it has not style from the style.css file and my terminal says "HTTP/1.1 GET /style.css" - 404 Not Found. When I just open my index.html file in chrome without using the app.py file, though, it does have the style formatting. Any help with this? Thanks in advance. My code is as follows:
app.py:
import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
web.config.debug = True
class Index(object):
def __init__(self):
self.render = web.template.render('.')
def GET(self):
return self.render.index()
if __name__ == '__main__':
app.run()
index.html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css" />
<title>Basic Web Project</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
style.css:
p {
color: green;
font-size: 22px;
}
When you specify <link type="text/css" rel="stylesheet" href="style.css" /> you say to your web browser the following thing : The style.css is on the same level as the index.html
Let me give you and example:
/app
index.html
style.css
if you open index.html from your browser you go to the following url
file://some/directory/app/index.html
)it is the same as file://some/directory/app/ because the browser will always search for the index when displaying a web page )
and when in this index.html the browser finds the <link> that specified by you it will search for that style.css under the following url : file://some/directory/app/style.css
and of course that it will find that file.
Now the fun part.
When you open localhost:8080 it will display localhost:8080/index.html which works because your web app ( that python script that you run ) knows what to do when somebody goes to that url ( because you defined it in the urls variable and you created that class )
But when on this page the browser find the <link> tag he tries to go to localhost:8080/style.css which your web app dose not know how to handle because you did not specified it in your app .
Now the solution:
You must define a url for /style.css and a class that will render that web page for you.
Have you tried to add style.css to urls, your application knows nothing about /style.css get request, probably that's why it returns 404.

Categories