I'm learning Python and Flask, I have very little experience, but something that is impossible.
With the usual AJAX does not have any problems, but I decided to try sijax, and even a simple example does not work. I'm sure this is due to incorrect connection and initialization, because I did git clone from the official repository git hub, and everything worked.
In the three examples, sijax working and initialized in one-file application, I want to use in the blueprint
If i click on the Say Hi!
Traceback return : 127.0.0.1 - - [12/Sep/2016 14:19:56] "POST / HTTP/1.1" 400 -
app init.py
import os
from flask import (Flask,
redirect,
url_for,
session)
# from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect
from os import path
from .database import db
from werkzeug.contrib.fixers import ProxyFix
import flask_sijax
import hmac
from hashlib import sha1
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.wsgi_app = ProxyFix(app.wsgi_app)
db.init_app(app)
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'''
if app.debug == True:
try:
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
except:
pass
'''
with app.test_request_context():
db.create_all()
from .general import controllers as general
from .shop import controllers as shop
from .test import controllers as test
app.register_blueprint(shop.module)
app.register_blueprint(general.module)
app.register_blueprint(test.module)
flask_sijax.Sijax(app)
CsrfProtect(app)
#app.template_global('csrf_token')
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest()
#app.route('/')
def index():
return redirect(url_for('test.index'))
return app
test blueprint controllers.py
from flask import (render_template,
Blueprint,
g)
import flask_sijax
module = Blueprint('test',
__name__)
#flask_sijax.route(module, '/')
def index():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('test/hello.html')
template hello.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/sijax/sijax.js') }}"></script>
<script src="{{ url_for('static', filename='js/sijax/json2.js') }}"></script>
<script>{{ g.sijax.get_js()|safe }}</script>
</head>
<body>
Say Hi!
</body>
</html>
The reason was not working sijax, it was the fact that the {{csrf_token ()}} was not active
It is necessary to do so either: Say Hi!
Either connect to the html file:
<script type="text/javascript">
var csrfToken = "{{ csrf_token() }}"
</script>
Related
Basically, i have a function that returns valid img sources (ex: https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png)
When i try to display that image on html using flask, the image won't appear but a small icon of a image will be there, if i right click the icon and click "Open in new tab" it shows me the image but it just won't work on the html
My flask code:
from flask import Flask, render_template, redirect, url_for, request
import LightHub # My other script that contains the function
app = Flask(__name__)
#app.route('/')
def index():
return render_template('server.html', source=LightHub.crawl())
app.run(debug=True)
My HTML code (in the templates folder):
<html>
<head>
<title>Random Lightshot</title>
<meta charset="utf-8" />
</head>
<body>
<div class="prints" align="middle">
<img src="{{source}}" align="middle">
</div>
</body>
</html>
output: https://imgur.com/IGY0mnY
When I try this,
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('server.html', source='https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png')
it works.
That probably means that LightHub.crawl() is not returning what you think it is. I believe you can verify that by running something like this:
assert LightHub.crawl() == 'https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png'
I suspect that if you add that assert to your function, you'll find that it fails.
I tried implementing the code from this documentation https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/, but the custom error template I created for HTTP 404 error is not loading (it loads the default template for Flask). The method that handles the error is not being called and I'm not sure why. Am I implementing the errorhandler correctly?
_init_.py
from flask import Flask
app = Flask(__name__)
def create_app():
from flask_app.main.routes import main
from flask_app.testing_errors.routes import testing_errors
app.register_blueprint(main)
app.register_blueprint(testing_errors)
return app
run.py
from flask_app import create_app
# importing the create_app method above creates the flask application instance after executing the command: flask run
testing_errors/routes.py
from flask import Blueprint, render_template
testing_errors = Blueprint("testing_errors", __name__)
#testing_errors.errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
404.html
<html lang="en">
<head>
<title>404</title>
</head>
<body>
<h1>404 Page Not Found</h1>
</body>
</html>
since you are using a blueprint to handle the entire Flask app errors which is best practice you need app_errorhandler not errorhandler
#testing_errors.app_errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
refer to this doc https://flask.palletsprojects.com/en/1.1.x/api/?highlight=app_errorhandler#flask.Blueprint.app_errorhandler
I want to build a site. I have the index folder and the connected folder. Each folder also has a static folder. In the connected/static folder, I have the connected.css file, which I am trying to access, through my blueprint. However, the final page tries to access the connected.css from the index/static folder.
Where am I mistaking?
Useful code:
__init__.py:
from flask import Flask
from .index import index_routes
from .connected import connected_routes
def create_app():
app = Flask(__name__, template_folder="templates", static_folder="static")
app.register_blueprint(index_routes.index_bp)
app.register_blueprint(connected_routes.connected_bp, url_prefix='/connected')
return app
connected_routes.py
from flask import Blueprint
from flask import render_template
connected_bp = Blueprint('connected_bp', __name__, template_folder='templates', static_folder='static', url_prefix='/connected')
#connected_bp.route('/')
def connected():
return render_template('connected.html', title="Connected to Hattrick")
index_routes.py
from flask import Blueprint
from flask import render_template
index_bp = Blueprint('index_bp', __name__, template_folder='templates', static_folder='static')
#index_bp.route('/')
def home():
return render_template('index.html', title="The Best Match Predictor")
connected.html
<link href="{{url_for('static',filename='connected.css')}}" rel="stylesheet">
In the above line I have the problem.
Maybe give this a try:
<link href="{{url_for('connected.static',filename='connected.css')}}" rel="stylesheet">
For some elaboration: https://flask.palletsprojects.com/en/1.1.x/blueprints/#static-files
I build a simple REST api with Eve and Python.
from flask import redirect, send_from_directory, render_template
from eve import Eve
import os
PWD = os.environ.get('PWD')
public = os.path.join(PWD, 'public')
app = Eve(static_folder=public)
# serve index.html
#app.route('/')
def index():
return send_from_directory(public, 'index.html')
# start the app
if __name__ == '__main__':
app.run()
Where I just serve a static HTML files from /public folder when / is requested.
I'm using bower to install bootstrap:
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap-theme.css">
But the problem is that the files are not being found although the path is correct.
Can someone explain me why is this happening?
It took me ages to figure this out. You have to import send_from_directory explicitly and also use __name__
from eve import Eve
from flask import send_from_directory
app = Eve(__name__, static_folder="static")
#app.route('/')
def index():
return send_from_directory("static", 'index.html')
app.run()
Then in settings.py:
URL_PREFIX="api"
Static file delivery:
http://127.0.0.1:5000/
http://127.0.0.1:5000/static/images/image.jpg
http://127.0.0.1:5000/static/css/style.css
API calls:
http://127.0.0.1:5000/api/person/
Apparently the path for my bower_components should be /public/bower_components/../../
I found in another thread a question regarding templates and it works quite well for static files, too:
template_folder = os.path.join(os.path.dirname(__file__), 'templates')
static_folder = os.path.join(os.path.dirname(__file__), 'static')
app = Eve(settings=settings, static_url_path='/static', template_folder=template_folder, static_folder=static_folder)
I want to show an image in the homepage of a python web application. So far I wrote the following program:
My directories and files
myWebApp/
app/
__init__.py
views.py
templates/
home.html
static/
Desert.jpg
run.py
__init__.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import render_template
from flask import url_for
#app.route('/')
def root():
imag = url_for ('static', filename = 'Desert.jpg')
tle = "Hey"
return render_template('home.html', imag,tle)
home.html
<html>
<title>{{ tle }}</title>
<body>
<img src="{{ imag }}"/>
</body>
</html>
run.py
from app import app
if __name__ == "__main__":
app.run()
And when I run the run.py, I receive the following Internal Server Error:
What's wrong?
That's not the correct syntax for the render_template function. You need to use keyword arguments:
return render_template('home.html', imag=imag, tle=tle)