I'm making a web interface for my Raspberry Pi using Django.
I'm trying to execute python code which lights up a display by simply clicking a HTML button inside a Django Template.
I currently light up the LED display by running this on command line:
cd rpi/
sudo python bubbles.py
Which executes that ^ python code
However I might want like to change the .py file depending on the HTML ID:
sudo python file_name.py
Anyways, this script needs to be executed via web browser so I wrote a view ...but I have no idea how to link a script to a view.
My template:
graphics_list.html
{% extends "base.html" %}
{% block content %}
<h1>{{ title }}</h1>
<h1> Scrolling Raspberry Pi LED Selection </h1>
{% for obj in object_list %}
<h3><a href='{{ obj.get_absolute_url }}'>{{ obj.name }}</a></h3>
<img src="{{ obj.image.url }}" alt="..." class = "img-responsive"><br>
<p>Use</p>
{% endfor %}
{% endblock content %}
I really don't know where to begin, should I use AJAX for this, PHP?
Instead of answering your code question, I'll answer your approach question.
To run this script from the internet, you need a web server. This will be the agent that handles your web (HTTP) requests. These come on all sorts of flavours. Django is a web framework, designed for creating complex web sites easily. Django also comes with a web server which it uses to serve its content.
The most relevant part to you will be this: Django is overkill for your goal. It may cause confusion, but if you've already got it up and running, it may also be best to stick with it. If you're not comfortable with running a webserver, using Django's may save you time.
I'd start by breaking down the problem into smaller goals, like this:
Get the Django webserver started. Just enough to see some kind of Django sample page when you access the server from your web browser.
Learn how to edit the models.py so that you can "render" (show in the browser) whatever view you want.
Make the VIEW mentioned above have a link to another url (still on your web server). This will trigger a request to your server for a different url. This url will be handled by a different method in your models.py, which in turn will render some other view. For now, imagine this other view displaying "Yes, youve lit the LED" or "LED lighting completed". The new method needed to render this view will be where you hook your code into for running your script.
Instead of running the script, just print something to the console to ensure that your "hook" is working. print "***** SOON ILL REPLACE THIS WITH WHATEVER IS NEEDED TO RUN MY SCRIPT ****" and look for that in the console
Then learn how to execute python from Django, and drop it in there.
The solution is here: Executing Python script from Django shell
What about AJAX? Ajax for you will result in a slight user-interface improvement. I'd forget it entirely until you've got the core solution working. It is by no means required to run a script from the web.
Related
I am trying to serve multiple HTML Pages to a single page and then serve that final single page as a PDF. I have a total of 95 pages and I have already achieved this using the following stack;
Python/ Flask
WeasyPrint HTML to PDF Creator
Jinja Templating using include
{% include 'page1.html' %}
{% include 'page2.html' %}
...
...
{% include 'page95.html' %}
Heroku deployment
gunicorn and nginx along side Flask in production
My problem is, the final page takes more than 80seconds to display as a PDF(i.e: the final html page containing 95 other html pages). And Heroku can maintain a connection only for 28-30 seconds. Is there any way I can speed up this process of serving the final PDF?
Will multi-threading help this? (I may have to read up on how to do this - not an expert) I already have this in my app
app.run(threaded=True)
Apologies if I am using any unclear terms here.
After trying out a few things, I think the best way to reduce the time is to simply use Reportlab and make PDF out of single pages. Then I will be using
pyPDF2
to merge all those single pages into one single PDF file to download. I will mark this as the answer, if I am able to execute it successfully!
I don't know how dumb my problem is, but I really couldn't figure out how to solve it
So, I have a html page that is rendered by flask, the page contains a variable {{ log }} (string) that is initially empty.
#app.route('/some-roote')
def function(id,log='some string'):
return render_template('webpage.html',log= log)
When the page is rendered initially, everything works fine, ('some string' is displayed in the UI)
At some point of my execution, I would like to change the content of {{ log }} and display the new content to the user.
I tried doing:
logs = new content;
render_template('webpage.html',log= logs)
but nothing happened, literally, the string value doesn't change, the webpage doesn't refresh, and I don't get any errors...
Please help guys. what am I doing wrong?
Jinja2 templates cannot change a page without the browser refreshing, they are simply a way for you to place dynamic content on a page before sending it to the browser. To change your page while on the client's browser you'll need to use javascript.
You can perform an ajax call from the browser back to your server, which then the server can send back the updated log variable. However, you'll then need to use javascript again to update that text on the DOM.
The best library for this is jQuery. You can also use frameworks like AngularJS and EmberJS that help you with data binding (among many other things).
You'll have to branch out into javascript for this kind of interactivity. Unfortunately, Python does not run natively in the browser.
I have a bigger project to handle, so this is what I want to do:
I have a Server with an MySQL database and Apache webserver running on. I save some machine information data in the database and want to create a web app to see, e. g. if the machine is running.
The web app should be designed responsive, i. e. changing design in accordance to the screen resolution of the current used device. This is important because the app will be used from smartphones and tablets mainly, but should also work on a normal pc.
I wrote a Python programm for my machine to get the data, and another Python programm on my server receiving information and saving in the database.
So my job now is to create the "responsive website" for my smartphone etc.
Then I want to broadcast this with my webserver.
Another Point is, that the web app should be build dynamically.
If I add another machine to my database, it should appear on my web app to be clickable and then show the related information.
First I thought about doing this in HTML5 and CSS3, with the use of jQueryMobile.
But I never used javascript. I'm just experienced in the "old" HTML and CSS.
Is Django a better choice, since I'm quite experienced in Python?
Or do I need both perhaps?
I haven't worked with any webframework yet, please help me choosing.
Or do I need one at all?
It looks like your server layer is OK for getting server informations and storing informations in database. Done with python.
And now, if I can resume, you need :
a reponsive web client
notification features
dynamically able to display new set for html elements
Based on this, I doubt in the fact that you will find a complete already packaged solution. Django should have this kind of features but it is not my favorite approach for such custom requirements.
If I have to do this I would use :
NodeJS for serverside code managing notifications
AngularJS for clientside managing client (!) and clean dynamic DOM manipulation with directives.
CSS Framework like Foundation or Bootstrap where responsive is native
What I would do is :
Init Phase
install nodejs and yeoman
initialize an angular app
write basic nodeJS server with a basic HTTP service
test your HTTP service with curl & your app with chrome or FF
Integration Phase
write basic angular HTTP call to this service
add communication between Node and Python (See
Combining node.js and Python
or something like this)
Client & Look and feel phase
add CSS framework for responsive and use it (navbar, table...)
look at Angular directives, develop a directive for adding new DOM elements
Finish / Clean your code and rollout
My solution now is as follows:
I will use the bottle microframework for generating serverside dynamic html-pages on request.
This will cause me to reload the page everytime I want to see new machine information, but for now it is enough for me.
Later I can add AJAX for live monitoring (I know this is javascript, I think I have to learn it anyway.)
Thanks for your solutions though.
You can put Bootstrap too for making responsive website.
Follow the code below code in your index.html in Django template.
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% block head %}
:
:
{% endblock %}
{% block body %}
.
.
.
{% endblock %}
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</html>
I would like to change the logo of a website based on which menu is currently activated/seen by the user browsing the website.
For instance I have www.urltowebsite.com/menu1 = Header Logo 1
And then I have www.urltowebsite.com/menu2 = Header Logo 2
And on top of this I want to add an else statement stating that: If any other menu is selected, use header logo 3.
How can I make this possible with Python? I cant seem to wrap my head around what to define where and how to call up the different functions on the HTML website.
Oh and I insist doing this with Python. And preferably without any framework such as Django. But if needs be I can install web.py
EDIT:
Am I forced to go with php then? I would like to once and for all start utilizing Python on my web projects.
The website is made in simple HTML as I said first. The Javascript functions are only used to serve the HTML menu's through AJAX. Again this does not matter much for what I am trying to do, as menu's have classes and I can define those in php and thus change my logo/header.
What I want to do is to use Python in this instance. Here is a code snippet from the site:
<div id="header">
<span class="title"><img src="http://www.url.com/subfolder/images/logo.png"/>
</span>
</div>
And some more relevant to this:
<div id="menu">
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
<li>005</li>
<li>006</li>
<li>007</li>
<li>008</li>
</ul>
</div>
So can I use python here?
You're asking to do the wrong thing the wrong way.
In order to change the logo based on the URL in Python , you need Python to generate the page and know what that url is.
There are two ways to do that in Python:
Use an existing Web Framework
Write your own Web Framework
"Python" doesn't know or care what your URL is - the frameworks and support libraries ( Django, Pyramid, Bottle, Flash, Tornado, Twisted, etc) figure out what the URL is by an integration with an underlying web server ( though some have their own webserver coupled in ). Similarly, PHP doesn't really know or care what the URL is - that information comes from an integration with Apache or FCGI/Nginx/etc. PHP tends to ship with most/all of that integration done. It's also worth noting that PHP is not just a language, but a web framework. Python is just a language.
Most Python frameworks will be written to the WSGI spec and have a "request" object that has all the data you want ( and many use the WebOb librbary for that ).
If you plan on doing everything with static HTML files, then you have a few options:
have a single static directory. use javascript to figure out the addressbar location, and render the corresponding logo / write the headers & footers.
have a "template" directory of all your HTML. use a Python script build a static version of each website with the custom headers/footers and configure your webserver to serve a different one for each domain.
No, Python cannot run inside the HTML web page. If you're really serving plain HTML pages then you must use javascript to execute code in the browser once the page is loaded. However, since you mention using AJAX, it sounds like it's not really true that you're serving plain HTML but rather have some server side code. If so, that server side code is the place to put your HTML-construction logic. To know the best way to do that, you would have to describe what's happening on the server.
Although I haven't used it, I have heard that the pyhp project more or less provides php-like embedded functionality for python.
I have a html page that contains a form and I would like a user to be able to input some data in the form. I would then retrieve this data with a python script.
I don't understand how to make the html and python communicate. How can the python retrieve the form after the user has clicked on post? Is there a basic example I can use to demonstrate this?
What you need is an HTTP server. Python can be used to make a server, or you could get one such as Apache or Lighttpd. I wrote an example application (Rock, Paper, Scissors) based off of this a while ago: https://dl.dropboxusercontent.com/u/95437705/RPS_Web.tgz
C0deH4cker is right that you should have your python program running somewhere in some kind of web server.
A proper way to do this for larger projects is to use a web framework like Django or Web2py. These frameworks have excellent documentation and tutorial pages that are well worth the effort of consuming. A smaller benefit is that both have their own built-in webserver for development an small deployment.
Another way is to write python code that has a web server of its own. You could have a look at Twisted, the networking framework for python. Good info is at http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html.
Finally -- but this is considered a bit outdated, I guess (??) -- there is the CGI option you describe. Most web servers like apache and lighttpd have the option to run CGI scripts. CGI scripts are very simple programs that, in their simplest form, when run, output HTML code on their stdout. The webserver looks at the first ("shebang") line in the script to determine the script interpreter, executes the script, picks up the output and serves it over HTTP.
Specific provisions have been made in CGI for parameter passing. In the Python CGI module, these are obtainable through cgi.FieldStorage()
First for some HTML:
An HTML form has an "action" and a "method" attribute. Action is the URL (absolute, or relative to the current path) where it will send the form data to; Method is the method to use, usually for a form with a submit button this is "POST".
So if you have this HTML code running somewhere:
<html>
<body>
<form name="sample" action="cgi-bin/myscript.cgi" method="post">
Name: <input type="text" name="name"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
When the user presses the submit button, all input values are posted to the URL "myprogram.cgi".
A good text on what CGI code should look like is in http://docs.python.org/library/cgi.html .
Some code that should work is:
import cgi
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<body>\n"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
form = cgi.FieldStorage()
if "name" not in form:
print "<H1>Error</H1>"
print "Please fill in the name fields"
else:
print "<p>name:", form["name"].value
print "</body>"
Now, it is important that you realize that you have to make this code available on the specified URL from a web server. How you should do this depends on your web server.
On apache under linux, you would normally put the script in /var/www/cgi-bin. Possibly you should enable cgi execution in the apache configuration, as it may be switched off for security reasons.