I'm pretty new to programming and I've been learning python in my spare time. As a challenge to myself, I created a simple text adventure for a class project. This is not for a programming class, so the professor won't know how to compile a raw Python script, let alone have a Python interpreter on their Mac.
That being said, is it possible to run python from a browser? I'm imagining some HTML file that my professor, or anyone, can click that launches a browser and they can play my game from there.
I've learned about something called Django from my research on this subject. However, I have no idea what it is, nor how to implement it. Again, I'm pretty new to programming, so if you could "explain like I'm five", that would be great.
EDIT: I found this other thread where the OP asks a similar question, but I don't fully understand the approved answer:
execution python application from browser
Well, not really. Your basic browser generally supports 1 programming language, javascript.
However, you could use pythonanywhere" which is a hosted python environment.
You could also try skulpt which is a javacript implementation of python. I have never tried this myself.
You can host a website on an internal network and run the program from there. Read more about the Python CGI programming
here to make a form that will execute your script and print the result as a html page
For example you could have a form that will ask for input in textboxes: Name: _, Value: __, SUBMIT
After they press the button, the browser will then send a request to the python program, execute it, and display the result back to the client as a html webpage.
In addition, you do not need to install any other third-party modules if you are using a school computer. However, ask you teacher before hosting the website on the school network.
The problem is that your program is a "text adventure" which requires a lot more input/output management for a CGI program.
You can use this answer for other projects.
Anyway, here are the steps to setup the server:
1) Create a folder for your website and add a "index.html" file (it can be anything)
2) Add a favicon.ico file in the folder (this will speed up the connection) You can download this one
3) Put this python program in the folder (it will be used to host the website)
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()
from socket import gethostbyname, gethostname
def server(port):
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", port)
httpd = server(server_address, handler)
print "Server %s:%s started" % (gethostbyname(gethostname()), str(port))
httpd.serve_forever()
server(4) #You can change this. It is a port number
4) Create a cgi-bin folder
5) To make the website available, execute the program created in the step 3. To stop hosting it, just close the python console.
6) While the program is running, you can go into the browser and type the IP adress : port as the URL. You will see your index.html page and favicon.ico icon. Anyone who is connected to the same network can get to the website. You and only you can also get to the website in a browser by entering http:/localhost:port with "port" being the port you've set
7) The rest you need to manage yourself. I cannot create the full script because I do not know what is in your program. Read the link provided in the beginning and modify your program to make it work in the browser.
FYI: It is possible to host more than one website or an instance of the same website at once using different ports. And, you can set and read cookies using Python CGI
Please comment if something doesn't work because of an error in my answer. I will try to fix it.
All of the answers so far assume that your game is something that can be presented as a web app. You can only do that if you write or covert your program (or part of it) into Javascript, which may not actually work because the existing compilers (e.g. pyjs) are quite limited.
If you made your program in a GUI (using 'Tkinter', 'Pygame', wxPython, PyQt, etc.), your best option is to package your program into a Mac app using py2app or pyinstaller.
Related
I am trying to get an RPi3 robot to accept commands from both the Web and from a touchscreen/keyboard interface. I have a script that handles the keyboard and I am looking for that current script I have in Python to be expanded to accept real-time input from the web. As well as trying to figure out how to send the data to the script.
More detail is below but that is the basic question.
I created the robot using a raspberry pi and 3 arduinos controlling DC motors and servos to make the bot move. The program is written in Python and is run from the command line. when run it:
queries the active serial ports on the Raspberry
opens each available port
sends an integer to the receiving arduino
the arduino responds with an identifying integer so the RPI can name the port
then the script waits for user input like "Forward"
the command is translated and sent to the correct port
the robot moves
This all works perfect. Now I want to expand it. I want to keep this functionality intact and add in a web interface so I can control it from anywhere. I've tried a couple of different things with no success. I have installed apache and I am able to serve the pages with no problem, I can get the data on the page, but I can't figure out how to get the web page to send the data to the running arduino script. My issue stems from the fact that the bot control script needs to run independent of the web page. I want to still keep the same input now from the keyboard, but I also want it to accept the data from the web page. If I invoke the bot controller from the web page each time it will need to re-establish the port connections each time which takes up to 20 seconds...
I am thinking if I create a listening script I can have the website invoke the listener which will run only to receive the data from the web and pass it to the bot controller and back. But I am not sure how to do this or if this is even the best way.
I've looked at websockets, CGI/wsgi, Flask, writing a file, and JSON and I just can't seem to string it all together.
Thanks in advance and apologies if this is not in the right place or has been answered before. Also, I have not included any code as the only solid code is the bot controller. I am hoping someone with some real expertise can help me unravel this.
thanks in advance
KenV
I would say Flask is your best option. A simple example of how you could use it:
from my_robot_stuff import move_forward
#app.route('/move_forward')
def move_forward_flask():
move_forward()
return redirect('/')
Your html would then have a button that says move forward that directs to mysite.com/move_forward. flask would process it, run the code, then redirect back to the root.
I'm at beginner level, I've given my 2 months at basics level in python. I'm familiar with algorithms, matrix and etc programming stuffs into python.
I want to give my whole life to django. But problem is i don't anything about web python stuffs except starting server on it.
I've started my server using:
import http.server
import socketserver
PORT = 8000
def playServer():
handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print("Serving at port", PORT)
httpd.serve_forever()
But when i call my simple web page, It still shows the codes of python, Please take a look at SCREENSHOT.
Please help me, How to make web page using python coding? Also let me know, Am i capable to start giving time with django? I've heard django is a framework, So i should give basics time to learn some python web page stuffs? right?
HELP WOULD BE APPRECIATED!!
https://docs.djangoproject.com/en/1.8/intro/tutorial01/, you have a lot to learn my friend but this tutorial will teach you how to get setup/install Django and give you a good base to start up with. Good luck with learning my man, any questions just comment below. BTW what you just did was not even Django at all, it was just starting a local webserver in python.
Obviously, teaching yourself is the hardest way to learn any skill. If you really do want to learn django, or anything else life, you're going to have to commit yourself, be patient, and ready to fail.
If you're really serious about this, I would work through the Django Book. This covers every aspect of django to get you started.
You're going to run into problems early and often. When you do so, stop and consort the docs, never be afraid to look directly at the source code and as always, come to SO with specific questions.
To answer you're more specific question, Django is nice in the fact that it hides all of the code you have above. For instance, once you have it configured, the line below will start a local server and you'll be able to interact with your web app through a web browser.
python manage.py runserver
Looks like you're trying to execute the python script directly from browser.
First you must call the script from the command-line, then check the address on browser.
Also, you need to call the playServer() method at the end of the file to start the HTTP server.
then go the the address:port on your browser. It'll look something like this:
Now about the second question,
I'll highly recommend you to start with Flask instead of Django.
It's simpler than django and best for beginners, and does less magic.
Also, as soon as you're comfortable with flask, you can easily move to django and have more fun while playing with it thereafter.
I have a bunch of Google alerts set up as rss feeds that update in real time. What I want is to be able to store the new data the rss feed is sending out in a database.
After looking around I found Google and Superfeedr both offer hubs that do most of the work for you; however they both require a callback url (obviously). I do have an Apache server running on the machine I'm working off, it already has python enabled so I can run python scripts on my server. However at the moment its only accessible from within my LAN.
What my real question is, what do I do next? I know that in php you would just have a call back file that handles requests but I'm lost as to what to do in python. Would I write a script and give the google/superfeedr services a url to that script? What would be in the script? Specific imports needed?
Also, I just read that if you use XMPP you don't need a callback url. How does that work?
For the local LAN problem, the most commonly used solution is to use tuneling solutions like Passageway. They will temporarily expose a local port of your machine to the "outer" web.
Now, as for implementation, it's fairly easy to set things up. Python is similar to PHP in the sense that you'll have to write a script that listen on networking connection and then handles the HTTP requests you're getting from Superfeedr or Google. (it looks like you're not familiar with Python, why not stick to PHP then?)
Finally XMPP is a feature that only us (Superfeedr) offer. It solves the problem of exposing local ports because it works behind the firewall.
I've used web.py to create a web service that returns results in json.
I run it on my local box as python scriptname.py 8888
However, I now want to run it on a linux box.
How can I run it as a service on the linux box?
update
After the answers it seems like the question isn't right. I am aware of the deployment process, frameworks, and the webserver. Maybe the following back story will help:
I had a small python script that takes as input a file and based on some logic splits that file up. I wanted to use this script with a web front end I already have in place (Grails). I wanted to call this from the grails application but did not want to do it by executing a command line. So I wrapped the python script as a webservice. which takes in two parameters and returns, in json, the number of split files. This webservice will ONLY be used by my grails front end and nothing else.
So, I simply wish to run this little web.py service so that it can respond to my grails front end.
Please correct me if I'm wrong, but would I still need ngix and the like after the above? This script sounds trivial but eventually i will be adding more logic to it so I wanted it as a webservice which can be consumed by a web front end.
In general, there are two parts of this.
The "remote and event-based" part: Service used remotely over network needs certain set of skills: to be able to accept (multiple) connections, read requests, process, reply, speak at least basic TCP/HTTP, handle dead connections, and if it's more than small private LAN, it needs to be robust (think DoS) and maybe also perform some kind of authentication.
If your script is willing to take care of all of this, then it's ready to open its own port and listen. I'm not sure if web.py provides all of these facilities.
Then there's the other part, "daemonization", when you want to run the server unattended: running at boot, running under the right user, not blocking your parent (ssh, init script or whatever), not having ttys open but maybe logging somewhere...
Servers like nginx and Apache are built for this, and provide interfaces like mod_python or WSGI, so that much simpler applications can give up as much of the above as possible.
So the answer would be: yes, you still need Nginx or the likes, unless:
you can implement it yourself in Python,
or you are using the script on localhost only and are willing to take some
risks of instability.
Then probably you can do on your own.
try this
python scriptname.py 8888 2>/dev/null
it will run as daemon
Have been asked to print to a remote printer via a socket connection, and struggling with how to approach this. I'm already passing data back and forth to a computer on the same network (also via a socket connection), and generating a PDF and/or HTML file with it when necessary. The idea is for me to send that file from the web server to the local printer and print it without any action by the remote user.
I looked into some print libraries and an IPP/CUPS library, but I'm not sure if that code could live within my web app, or if it would have to live on a print server accessible by my web app that also can communicate with the printer (or something else - I'm really fumbling in the dark).
a) Does this sound plausible?
b) If so, can I control the printer entirely via the socket connection using code that lives on my web server, or will I need to write an application that lives on the client's machine (or network)?
Very unfamiliar working with hardware, so please forgive anything that sounds naive.
I am not sure that this is a good idea.
If I understand the question correctly, this is about printing from a web application. I suggest the users simply use the browser's built-in print function for printing the generated HTML (or the PDF reader's in the case of PDFs).
UPDATE
If you need to automatically print from your web application, I suggest you do the following in the web app:
Generate PDFs on disk
Shell out to lp: subprocess.Popen(['lp', '-d', printername, filename])
The remote printers should be set up in CUPS on the web server.