I have a view python file which has the code:
#app.route('/')
def index():
page = """
<html>
<head>
</head>
.....
...
</html>
I made some changes to this file , those just normal changes like importing render_template.I was able to see the html file using foreman start command in my localhost. However after some changes as I mentioned earlier , when I again start using foreman start I get an error - " View function mapping is overwriting an existing endpoint function: index "
However when I used #app.route('/',endpoint ="new"), it worked.
Looks like it reserving some endpoints and not letting me override it. How can I remove all the endpoints to start fresh.
Make sure you don't have two routes with the same URI.
Related
After exposure to Svelte/Rollup in the JavaScript world I was impressed that it could refresh the browser automatically when changes were made to the source code. Seeking a similar behaviour in Python I found the package livereload that supports integration with Flask (pretty sure using the same tech). I want the result of the refresh to reflect ALL changes to the source code.
I am using WSL with livereload v2.5.1 and viewing via Chrome. I can successfully get the page to refresh on a detected source code change but the refresh doesn't re-download the new files and just displays the cached files. The page does refresh but I need to hit Ctrl + click refresh to see the actual changes. Using developer mode and turning off caching works as desired. Using Svelte/Rollup doesn't require disabling caching to see source changes.
Most of my changes are to *.css or *.js files served from the 'static' folder in a standard Flask project template and rendered using the 'render_template' function of Flask.
I'm launching my Flask server as follows:
app = create_app()
app.debug = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
server = Server(app.wsgi_app)
server.watch(filepath='static/*', ignore=lambda *_: False)
server.serve(liveport=35729, host='127.0.0.1', port=80)
I would like to not have to disable the cache so that the refresh triggered by livereload actually reflects the changes in the source. Is there a setting in Flask or livereload I can use to achieve this or is this a feature request for the livereload package?
Related Question:
How to automate browser refresh when developing an Flask app with Python?
UPDATE EDIT:
Further testing has shown that this is specifically an issue with Chrome, with Firefox it works as expected out of the box. Digging into the underlying livereload.js library it seems there is a parameter of 'isChromeExtension' which I have tried to force set to True but had no effect.
I came across the same issue and here is what I did to solve the issue.
As you mentioned this is a browser caching problem. So we want invalidate the cached css/js files. We can achieve this by setting a version on the static file. We want the version to change each time you make changes to the css file. What I did feels a bit hacky but you'll get the idea.
Here is what I have for my html template
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<link href="{{ url_for('static', filename='main.css', version=time)}}" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="hello-color">
{{ message }}
</h1>
</body>
</html>
You can see version=time I am passing the template the current time with the following.
from flask import Flask, render_template
from time import time
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('hello.html', message="Hello World!", time=time())
from time import time and
time=time()
And finally my main python file
from app import app
from livereload import Server
if __name__ == '__main__':
server = Server(app.wsgi_app)
server.serve(port=2200, host='0.0.0.0')
Hopefully this helps you or anyone else running to this issue.
i just would like to run a python script by clicking on a html button.
python script is reallly simple. when you run it, it just add a "name" and "age" data in my database.
import sqlite3
conn = sqlite3.connect('bdaremplir.sqlite')
cur = conn.cursor()
"""cur.execute('DROP TABLE IF EXISTS latable')
cur.execute('CREATE TABLE latable (noms TEXT, age INTEGER)')"""
nom = 'TheName'
age = 100
cur.execute('''INSERT OR IGNORE INTO latable (noms, age) VALUES ( ?, ? )''', (nom, age))
conn.commit()
and the basics of html
<!DOCTYPE html>
<html>
<head>
<title>visualisateur</title>
</head>
<body>
<button></button>
</body>
</html>
now from here i don't at all what i can do.
if anyone can help... thank you.
Web browsers only know how to run JavaScript, not Python, so unless you really want to run Python in the browser1, you have to learn about the client-server architecture of the web.
Basically, you have to
make your Python program available as a web server, and
send a request to that server when your HTML button is clicked.
Running a web server
There are many ways to implement a web server in Python. When you get to writing a proper application, you'll probably want to use a library like Flask, Django, or others. But to get started quickly, you can use the built-in Python HTTP server with CGI:
Create a Python script named handle_request.py with the following content:
#!/usr/bin/env python3
print("Content-Type: text/plain\n")
print("hello world")
and put it into the cgi-bin directory next to your HTML file and make sure you can run it by typing "handle_request.py" into the console;
2. Run the built-in HTTP server:
python3 -m http.server --bind localhost --cgi 8000
Open http://localhost:8000 in your browser to access the server.
You should see the listing of the directory, including your HTML file and the cgi-bin directory. Clicking the HTML file should display it in the browser (with a URL like http://localhost:8000/test.html), and opening http://localhost:8000/cgi-bin/handle_request.py will run the script we've created and display its response as a web page. You can add your code to the script, and it will run whenever the browser accesses its URL.
Making a request from your web page
Now the question is how to make the browser access the http://localhost:8000/cgi-bin/handle_request.py URL when a button on your page is clicked.
To do that you need to invoke the API for making requests from JavaScript. There are different ways to do that (e.g. XMLHttpRequest or jQuery.ajax()), but a simple way that works in the modern web browsers is fetch():
<button id="mybutton"></button>
<script>
document.getElementById("mybutton").onclick = async function() {
let response = await fetch("http://localhost:8000/cgi-bin/handle_request.py");
let text = await response.text();
alert(text);
}
</script>
Now when you click the button, the browser will make a request to the specified URL (thus running your script), but instead of displaying the results as a web page in a tab, it will be made available to your JavaScript.
notes
1 ...which you probably don't at this point, but if you do, see the pointers by Michael Bianconi.
I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.
My question is about how to serve multiple urls.py (like urls1.py, urls2.py and so on) files in a single Django project.
I am using Win7 x64, django 1.4.1, python 2.7.3 and as a server django dev-server tool.
I have decided to use a method which i found by google from
http://effbot.org/zone/django-multihost.htm
I have created a multihost.py file and put in to the django middleware folder:
C:\python27\Lib\site-packages\django\middleware\multihost.py
With the following code:
from django.conf import settings
from django.utils.cache import patch_vary_headers
class MultiHostMiddleware:
def process_request(self, request):
try:
host = request.META["HTTP_HOST"]
if host[-3:] == ":80":
host = host[:-3] # ignore default port number, if present
request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
except KeyError:
pass # use default urlconf (settings.ROOT_URLCONF)
def process_response(self, request, response):
if getattr(request, "urlconf", None):
patch_vary_headers(response, ('Host',))
return response
Also in my project setting.py file i have added a mapping dictionary like the link above shows:
# File: settings.py
HOST_MIDDLEWARE_URLCONF_MAP = {
"mysite1.com": "urls1",
#"mysite2.com": "urls2"
}
I did not yet implemented the error handling like described by the link above.
My hosts file includes the follwoing:
127.0.0.1 mysite1.com
Project structure is the following:
effbot django project folder:
+ effbot
--- settings.py
--- view.py
--- wsgi.py
--- urls.py
--- urls1.py
+ objex
--- models.py
--- views.py
+ static
--- css
--- images
There is no templates folder, because i dont serve html items from files, they are coming from databsse (i doubt that my problem is in this).
Now the problem is: when i go for the adress
mysite1.com
in my browser with django dev-server launched i get code 301 from the server. And browser shows "cannot display page" message.
Could you please explain me how to use mentioned method? I'm new to django and haven't done any real projects yet. Just have read the docs and launched a couple of sites at home to learn how it works.
I expect that urlconfs will be called in dependance from incoming
request.META["HTTP_HOST"]
The target is to serve different urlconfs for mysite1.com and mysite2.com
in a single django project.
I think this should to work some how.
Thank you for any feedback.
EDIT:
After some research attempts i found that i plugged my multyhost.py incorrectly in settings.
Fixed now. But the same result still.
Also i found out that my django dev-server tool is not reflecting anyhow that it handles any requests from the browser (IE9) except when i do "http://127.0.0.1".
May be i have to try some production server for my task, like nginx?
Your ROOT_URLCONF should be effbot.urls without .pyas you can see in the example in the documentation.
Also, HOST_MIDDLEWARE_URLCONF_MAP should reflect the ROOT_URLCONF so add `effbot. like this:
HOST_MIDDLEWARE_URLCONF_MAP = {
"mysite1.com": "effbot.urls1",
#"mysite2.com": "effbot.urls2"
}
One more thing, please try with another browser (Chrome, Firefox), sometimes I had problems accessing dev server with IE.
Is there any way to get pyramid absolute application url in main() function?
I want to add it into global settings, so it could be called every where(in templates and js files).
In pyramid documents there is some functions would help, but all of them need a request object and must call in a view.
Thanks.
Pyramid (like most WSGI applications) can be mounted on any domain and url prefix. Thus the application itself doesn't actually know what urls it is responsible for unless you code that into your application specifically (an INI setting, for example).
This is why request.application_url exists... because the application_url could be different per request based on how many different domains and url prefixes you have that are proxying requests to your application.
I just get the full route for my index route, 'home' in my case:
I set this in my main wrapper mako template so that all of my JS calls can reference it to build a proper path for ajax calls/etc
<script type="text/javascript" charset="utf-8">
<%
app_url = request.route_url('home').rstrip('/')
%>
APP_URL = '${app_url}';
</script>