I am following this simple tutorial for creating a pinterest clone.
http://blog.jetbrains.com/pycharm/2013/12/video-pycharm-web-magic-building-a-pinterest-clone/
I'm having trouble getting Angular to work.
html code:
<!DOCTYPE html>
<html>
<head>
<title>Pin Clone</title>
</head>
<body ng-app1="app1" ng-controller="AppCtrl as app1">
{{ app1.message }}
<script src="bower_components/angular/angular.js"></script>
<script src="js/app1.js"></script>
</body>
</html>
app1.js code:
var app1 = angular.module("app1", []);
app1.controller("AppCtrl", function () {
var app1 = this;
app1.message = "not working"
})
When I reload the page I simply get to see the text:
{{ app1.message }}
This is in the browser.
Console states this on reload:
127.0.0.1 - - [07/Jun/2014 12:59:50] "GET / HTTP/1.1" 304 -
127.0.0.1 - - [07/Jun/2014 12:59:50] "GET /bower_components/angular/angular.js HTTP/1.1" 304 -
127.0.0.1 - - [07/Jun/2014 12:59:50] "GET /js/app1.js HTTP/1.1" 304 -
This is on Ubuntu 14.04. I'm using Bower to install Angular into the project.
AngularJS version 1.2.17
Bower 1.3.4
node version v0.10.28
npm version 1.4.9
Project Folders:
Edit 1, Flask Code in Home_Site.py:
from flask import Flask
from flask.ext.restless.manager import APIManager
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, Text
# instantiating Flask
app = Flask(__name__, static_url_path='')
# setting the SQLALCHEMY_DATABASE_URI to the pin database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pin.db'
# setting an instance of SQLAlchemy
db = SQLAlchemy(app)
# creates a database model with an id, title, image
class Pin(db.Model):
id = Column(Integer, primary_key=True)
title = Column(Text, unique=False)
image = Column(Text, unique=False)
db.create_all()
# automatically creates an api for the pins in the db
# api stands for application programming interface
api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Pin, methods=['GET', 'POST', 'DELETE', 'PUT'])
# type route and hit tab to create this
# this allows you to route to the main html file in the static folder
#app.route('/')
def index1():
return app.send_static_file('index1.html')
# reloads the server on its own
app.debug = True
if __name__ == '__main__':
app.run()
You have a typo in your ngApp declaration:
<body ng-app1="app1" ng-controller="AppCtrl as app1">
should be:
<body ng-app="app1" ng-controller="AppCtrl as app1">
(Note the lack of 1 in the ng-app declaration.)
You need to load your static resources through the /static route:
<script src="/static/bower_components/angular/angular.js"></script>
<script src="/static/js/app1.js"></script>
This also means you need to move your js folder into the static folder of your project.
Related
I'm trying to display an image on a simple website, which I am using Flask for. I already tried to do this using a js script on the website itself, but it didn't work.
However, I do not know how to periodically update/refresh the image.
I'm using html and javascript for the first time right now and I'm too confused to get it to work.
This is the main .py file:
from flask import Flask, render_template
import os
#sorry for the bad code :/
app = Flask(__name__)
#app.route("/")
def running():
return "<p>Website running!</p>"
app.config['UPLOAD_FOLDER'] = os.path.join('static','images')
#app.route("/chart")
def show_img():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'chart.png')
return render_template("chart.html", user_image = full_filename)
if __name__ == "__main__":
app.run(port=3000)
This is chart.html:
<!DOCTYPE html>
<html>
<body>
<img src={{ url_for("static", filename="images/"+"chart.png" ) }}/>
</body>
</html>
What is the easiest way to update/reload the image every 5 seconds?
The filename stays the same, but the image itself changes
Some notes:
When working inside a request, it is better to use current_app
from Flask import current_app
#app.route("/chart")
def show_img():
# current_app.config
full_filename = os.path.join('images', 'chart.png')
return render_template("chart.html", user_image=full_filename)
We removed static as we'll be using static in the template itself.
Since you already have the user_image variable, you can add it to the file directly
<!DOCTYPE html>
<html>
<body>
<img src={{ url_for("static", filename=user_image ) }}/>
</body>
</html>
This will display the image.
Dealing with uploads
If you want to implement uploads etc, use flask-reuploaded, a maintained fork of Flask-uploads.
On the front-end, you need a file upload form. Then you need a route to accept the uploaded file. Then you need to make sure that the uploaded filename is always the same, maybe by deleting existing files beforehand.
A complete demo
Following the official docs, here is a demo.
Folder structure
.
├── app.py
├── static
│ └── images
├── templates
└── chart.html
chart.html
<!DOCTYPE html>
<html>
<body>
<form method="post" enctype=multipart/form-data action="/upload">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<br>
<img src={{ url_for("static", filename=user_image ) }}/>
</body>
</html>
app.py
import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
current_file = ''
#app.route("/")
def running():
return "<p>Website running!</p>"
app.config['UPLOAD_FOLDER'] = os.path.join('static','images')
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/upload', methods=['GET', 'POST'])
def upload_file():
global current_file
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
current_file = filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('show_img', name=filename))
#app.route("/chart")
def show_img():
filename = os.path.join('images', current_file)
return render_template("chart.html", user_image=filename)
if __name__ == "__main__":
app.run(port=3000)
I have a bigger testcase which uses Pyramid and Mako and also Javascript. It works fine unless I put the Javascript code into a separate file. Then it fails.
I have reduced the test case to the following (3 files) replacing the JS file with a simple picture I wanted to load but that fails too with the same error message:
NotImplementedError: Can't perform this operation for unregistered loader type
127.0.0.1 - - [15/Oct/2021 10:46:44] "GET /static/system6.jpg HTTP/1.1" 500 59
127.0.0.1 - - [15/Oct/2021 10:46:44] "GET /favicon.ico HTTP/1.1" 404 164
post_trypyramid.py:
from pyramid.config import Configurator
if __name__ == '__main__':
with Configurator() as config:
config.include("pyramid_mako")
config.add_route('home', '/')
config.add_route('system', '/system')
config.add_static_view(name='static', path='static')
config.scan('post_trypyramid_views')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
post_pyramid_views.py:
from pyramid.httpexceptions import HTTPFound, HTTPNotFound
from pyramid.response import Response
from pyramid.view import view_config
#view_config(route_name='home')
def home_view(request):
return Response('<p>Welcome</p>')
#view_config(route_name='system', renderer='post_trypyramid_template.mako')
def form_view(request):
return {"Nothing": "nothing"}
post_trypyramid_template.mako:
<head>
<title>My SANDBOX</title>
<meta charset="utf-8"/>
</head>
<body>
<h1>Settings:</h1>
<img src="static/system6.jpg" alt="Here you should see an image">
<img src="{{ request.static_url('__main__:static/system6.jpg') }}" alt="Here you should see an image" >
</body>
</html>
I start the application in "C:/Users/myAccount/Projects/TryPyramid" but no image is shown on the webpage, only the heading.
If I replace the "add_static_view()" call above with the absolute path like
"config.add_static_view(name='static', path='C:/Users/myAccount/Projects/TryPyramid/static')"
then at least the first "<img ...>" leads to an image in the browser.
So what is wrong with my relative path setting?? Or what else do I miss?
I have tried all sorts of modifications, like trailing or leading slashes. Nothing helped
Any hint welcome. Thanks.
You are using Jinja2 syntax in a Mako template. As an aside, you should use the project name, not __main__. Try this:
<img src="${ request.static_url('myproject:static/system6.jpg') }" alt="Here you should see an image" >
If you use pyramid-cookiecutter-starter to create a starter project using Mako as the templating engine, then you can see other examples of how to build a project and proper syntax. See the documentation for a tutorial.
I have the following code for an flask server:
from flask import render_template
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
# Create a URL route in our application for "/"
#app.route("/")
def home():
"""
This function just responds to the browser URL
localhost:5000/
:return: the rendered template "home.html"
"""
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5100)
Which works fine, but I need to add CORS support, so I intalled the library:
pip3 install -U flask-cors
And the lines:
from flask_cors import CORS
CORS(app)
The rest remains the same:
from flask import render_template
from flask_cors import CORS
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
CORS(app)
# Create a URL route in our application for "/"
#app.route("/")
def home():
"""
This function just responds to the browser URL
localhost:5000/
:return: the rendered template "home.html"
"""
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5100)
But now, when I try to run it I get, this error:
Traceback (most recent call last):
File "server.py", line 15, in <module>
CORS(app)
File "/home/luis/.local/lib/python3.6/site-packages/flask_cors/extension.py", line 129, in __init__
self.init_app(app, **kwargs)
File "/home/luis/.local/lib/python3.6/site-packages/flask_cors/extension.py", line 154, in init_app
app.after_request(cors_after_request)
AttributeError: 'FlaskApp' object has no attribute 'after_request'
It works below.
I think it's solved...
https://github.com/zalando/connexion/issues/438
from flask import render_template
from flask_cors import CORS
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
CORS(app.app) # this
# Create a URL route in our application for "/"
#app.route("/")
def home():
"""
This function just responds to the browser URL
localhost:5000/
:return: the rendered template "home.html"
"""
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5100)
My issue was adding the CORS line before the adding the yml files, also passing *.app to the CORS method instead.
flask_server = connexion.App(__name__) # pylint: disable=invalid-name
flask_server.add_api("api.yaml", strict_validation=True)
CORS(flask_server.app)
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 3 years ago.
Loading the route index() with index.html works - it extends from base.html. As do some other templates which do not have <arguments> in the route path.
However, at app.route('/channel/') I see Flask Server trying to serve statics (loaded from base.html) from /channel/static/etc instead of /static/etc and thus, the CSS fails to render. Whatever I put in that app.route('/here/') is where Flask tries to render statics from on that page: /here/static/etc and hence the CSS/JS 404s.
I've tried changing the loading of static content in base.html from the below:
<link href="static/css/font-face.css" rel="stylesheet" media="all">
to
<link href="/static/css/font-face.css" rel="stylesheet" media="all">
This hasn't fixed the issue. I eventually got a blank page with no content rendering at all. Made me think its something to do with the app.route() function.
App structure:
<dock>
<bot>
<nginx>
<zigweb>
<app>
<templates>
base.html
etc.html
<static>
<css>
<etc>
I'm using the Flask development server.
console on loading channel.html
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:58:08] "GET /channel/launch_logic HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:58:09] "GET /channel/static/images/icon/signally.png HTTP/1.1" 404 -
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:58:09] "GET /channel/static/images/icon/avatar-icon.png HTTP/1.1" 404 -
console on loading index.html
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:59:19] "GET / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:59:20] "GET /static/vendor/animsition/animsition.min.css HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:59:20] "GET /static/vendor/font-awesome-4.7/css/font-awesome.min.css HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [08/Nov/2019 13:59:21] "GET /static/vendor/bootstrap-4.1/bootstrap.min.css HTTP/1.1" 200 -
BASE.HTML
https://pastebin.com/9FgqE2z9
CHANNEL.HTML
{% extends "base.html" %}
{% block content %}
<h1>hello</h1>
{% endblock %}
Routes.py (for channel())
#app.route('/channel/<username>')
def channel(username):
user = User.query.filter_by(username=username).first()
return render_template('channel.html', user=user)
In base.html youve specified the URL for the images as static/images/icon/signally.png. In this case the URL in relative to the current path, thus it becomes /channel/static/images/icon/signally.png as the base for the current path is /channel/.
You can change the image source to src="/static/images/icon/signally.png" and it would correctly resolve the path.
Or, which is probably more desirable, you can use url_for('static', '<filename>') as someone mentioned in the comments. In that case, Flask will automatically resolve the image source for you. One of the benefits is that if you have a custom static folder for a blueprint, you dont need to worry about specfying it explicitely, but you'll only need to write the relative name of the file.
My Python Program is,
from xbee import ZigBee
import serial
import sys
sPort = serial.Serial("/dev/ttyAMA0", 9600)
xbee = ZigBee(sPort)
targStr = sys.argv[1]
data = str(targStr)
print (data)
destAdd = "\x00\x13\xa2\x00\x40\xa9\xcc\xad"
xbee.send("tx",dest_addr_long=destAdd,dest_addr="\xff\fe",data=data)
print ("Sent!")
When I execute this python program on linux shell, it works all great! How do execute this program on certain event from HTML Page (Either using Javascript, AJAX or PHP) ?
You need to embed this code into some Python web server - for example Flask.
See example bellow - xbee_test.py (it is very raw, don't use that in production environment):
from flask import Flask
app = Flask(__name__)
from xbee import ZigBee
import serial
sPort = serial.Serial("/dev/ttyAMA0", 9600)
xbee = ZigBee(sPort)
#app.route("/<data>")
def index(data):
destAdd = "\x00\x13\xa2\x00\x40\xa9\xcc\xad"
xbee.send("tx",dest_addr_long=destAdd,dest_addr="\xff\fe",data=data)
return "Sent!"
if __name__ == "__main__":
app.run()
Now, when you run this in Python and hit http //localhost:5000/test_data you get your code executed.
Embedding this into HTML page as e.g. AJAX call is from this point on uncomplicated.
Here is how to obtain Flask installation and run that:
$ pip install Flask
$ python xbee_test.py
* Running on http://localhost:5000/