I've tried various different ways to open an HTML file from python code, but each time I get a '500 internal server error'.
Here is my python script:
if (variable == "0, User and IP logged"): #conditional to check if user's credentials were accepted by the API
page = urllib.urlopen("mainPage.html").read()
print page
#html file is opened and read - NOT WORKING!
Here is my html file:
<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>
How do I get the python script to display my hello world page?
My tutor said I should use open(), but I'm not sure how.
First of all you need to run Web Server which will server web pages :
Here I am using sample bottle web framework
bottle_server.py
from bottle import route, run
#route('/')
def dashboard():
return '<b>This is index page</b>'
run(host='localhost', port=8080)
Run script using
python bottle_server.py
Now, Server is running on localhost on port 8080
Here is sample python script
Client.py
import urllib
print urllib.urlopen('http://localhost:8080/").read()
Run client script using
python Client.py
This will produce output like
<b>This is index page</b>
Try this one...
webbrowser.open_new_tab('helloworld.html')
Related
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.
my goal is to be able to use beutifulsoup4 with Python3.4 in a flask web-app all with a elastic-beanstalk server and be able to use beautifulsoup within my main script. I have succeeded in getting a elastic beanstalk web app with flask and python 3.4 up and running smoothly with this code:
from flask import Flask
import time
# print a nice greeting.
def say_hello(username = "World"):
return '<p>Hello %s!</p>\n' % username
# some bits of text for the page.
header_text = '''
<html>\n<head> <title>EB Flask Test</title> </head>\n<body>'''
instructions = '''
<p><em>Hint</em>: This is a RESTful web service! Append a username
to the URL (for example: <code>/Thelonious</code>) to say hello to
someone specific.</p>\n'''
home_link = '<p>Back</p>\n'
footer_text = '</body>\n</html>'
# EB looks for an 'application' callable by default.
application = Flask(__name__)
# add a rule for the index page.
application.add_url_rule('/', 'index', (lambda: header_text +
say_hello() + instructions + footer_text))
# add a rule when the page is accessed with a name appended to the site
# URL.
application.add_url_rule('/<username>', 'hello', (lambda username:
header_text + say_hello(username) + home_link + footer_text))
if __name__ == "__main__":
# Setting debug to True enables debug output. This line should be
# removed before deploying a production app.
application.debug = True
application.run()
requirements file looks like this:
flask==0.12.2
beautifulsoup4==4.6
lxml==4.1
up until this point every thing is OK with no errors, but once I import beautifulsoup in line 3 of the python code the web page gives me this error:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable
to complete your request.
Please contact the server administrator at root#localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
if anyone is able to provide advice or let me know if i am being to broad pleas let me know:)
thanks again, john D.
Im using Python bottle framework to upload a file..The controller receives the file and transmits to another system using Java rest service..
Everything works fine when the file is small but if the file is huge (it takes 5 mints) the application returns a blank page instead of a html page that its supposed to return.
#app.route('/DataLoads',method='GET')
def pptriv():
return template('dataload',
footer_html=FOOTER_HTML,feedback_html=FEEDBACK_HTML)
#app.route('/DataLoads',method='POST')
def pptriv():
username = request.forms.get('username')
password = request.forms.get('password')
uploadfile = request.files.get('File Upload')
....
..use Python requests module to transmit the files.....
...
print 'r.status_code = ', r.status_code
return template('dataload',
footer_html=FOOTER_HTML,feedback_html=FEEDBACK_HTML)
I see the print stmt r.status_code but the dataload html page, if its small file everything looks good..
Have you tried increasing MEMFILE_MAX?
import bottle
bottle.BaseRequest.MEMFILE_MAX = 1024 * 1024 * 200
Python bottle module causes "Error: 413 Request Entity Too Large"
Also: are you using a browser or a command-line client to upload the file? If browser, then I'd suggest using curl to see exactly what (if anything) is returned from your server.
I used to create web app in the same computer, but if the server and the client is not in the same computer, how can we access to the web page ?
I mean, for example I have an html form and a button "ok" :
If the server and the client are in the same computer, in action = " " we put localhost/file.py , but if the server and the client are not in the same computer how to do this ? Because the client can't to have localhost in his webbrower (url).
The "action" part of a form is an url, and If you don't specify the scheme://host:port part of the URL, the client will resolve it has the current page one. IOW: just put the path part of your script's URL and you'll be fine. FWIW hardcoding the scheme://host:port of your URLs is an antipattern, as you just found out.
Your script is supposed to be run as a CGI script by a web-server, which sets environment variables like REMOTE_ADDR, REQUEST_METHOD ...
You are running the script by yourself, and this environment variable are not available.
That's why you get the KeyError.
Github offers to send Post-receive hooks to an URL of your choice when there's activity on your repo.
I want to write a small Python command-line/background (i.e. no GUI or webapp) application running on my computer (later on a NAS), which continually listens for those incoming POST requests, and once a POST is received from Github, it processes the JSON information contained within. Processing the json as soon as I have it is no problem.
The POST can come from a small number of IPs given by github; I plan/hope to specify a port on my computer where it should get sent.
The problem is, I don't know enough about web technologies to deal with the vast number of options you find when searching.. do I use Django, Requests, sockets,Flask, microframeworks...? I don't know what most of the terms involved mean, and most sound like they offer too much/are too big to solve my problem - I'm simply overwhelmed and don't know where to start.
Most tutorials about POST/GET I could find seem to be concerned with either sending or directly requesting data from a website, but not with continually listening for it.
I feel the problem is not really a difficult one, and will boil down to a couple of lines, once I know where to go/how to do it. Can anybody offer pointers/tutorials/examples/sample code?
First thing is, web is request-response based. So something will request your link, and you will respond accordingly. Your server application will be continuously listening on a port; that you don't have to worry about.
Here is the similar version in Flask (my micro framework of choice):
from flask import Flask, request
import json
app = Flask(__name__)
#app.route('/',methods=['POST'])
def foo():
data = json.loads(request.data)
print "New commit by: {}".format(data['commits'][0]['author']['name'])
return "OK"
if __name__ == '__main__':
app.run()
Here is a sample run, using the example from github:
Running the server (the above code is saved in sample.py):
burhan#lenux:~$ python sample.py
* Running on http://127.0.0.1:5000/
Here is a request to the server, basically what github will do:
burhan#lenux:~$ http POST http://127.0.0.1:5000 < sample.json
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: text/html; charset=utf-8
Date: Sun, 27 Jan 2013 19:07:56 GMT
Server: Werkzeug/0.8.3 Python/2.7.3
OK # <-- this is the response the client gets
Here is the output at the server:
New commit by: Chris Wanstrath
127.0.0.1 - - [27/Jan/2013 22:07:56] "POST / HTTP/1.1" 200 -
Here's a basic web.py example for receiving data via POST and doing something with it (in this case, just printing it to stdout):
import web
urls = ('/.*', 'hooks')
app = web.application(urls, globals())
class hooks:
def POST(self):
data = web.data()
print
print 'DATA RECEIVED:'
print data
print
return 'OK'
if __name__ == '__main__':
app.run()
I POSTed some data to it using hurl.it (after forwarding 8080 on my router), and saw the following output:
$ python hooks.py
http://0.0.0.0:8080/
DATA RECEIVED:
test=thisisatest&test2=25
50.19.170.198:33407 - - [27/Jan/2013 10:18:37] "HTTP/1.1 POST /hooks" - 200 OK
You should be able to swap out the print statements for your JSON processing.
To specify the port number, call the script with an extra argument:
$ python hooks.py 1234
I would use:
https://github.com/carlos-jenkins/python-github-webhooks
You can configure a web server to use it, or if you just need a process running there without a web server you can launch the integrated server:
python webhooks.py
This will allow you to do everything you said you need. It, nevertheless, requires a bit of setup in your repository and in your hooks.
Late to the party and shameless autopromotion, sorry.
If you are using Flask, here's a very minimal code to listen for webhooks:
from flask import Flask, request, Response
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def respond():
print(request.json) # Handle webhook request here
return Response(status=200)
And the same example using Django:
from django.http import HttpResponse
from django.views.decorators.http import require_POST
#require_POST
def example(request):
print(request.json) # Handle webhook request here
return HttpResponse('Hello, world. This is the webhook response.')
If you need more information, here's a great tutorial on how to listen for webhooks with Python.
If you're looking to watch for changes in any repo...
1. If you own the repo that you want to watch
In your repo page, Go to settings
click webhooks, new webhook (top right)
give it your ip/endpoint and setup everything to your liking
use any server to get notified
2. Not your Repo
take the url you want i.e https://github.com/fire17/gd-xo/
add /commits/master.atom to the end such as:
https://github.com/fire17/gd-xo/commits/master.atom
Use any library you want to get that page's content, like:
filter out the keys you want, for example the element
response = requests.get("https://github.com/fire17/gd-xo/commits/master.atom").text
response.split("<updated>")[1].split("</updated>")[0]
'2021-08-06T19:01:53Z'
make a loop that checks this every so often and if this string has changed, then you can initiate a clone/pull request or do whatever you like