Unable to request the status code of localhost - python

I am using python and flask to create a web API. However I am getting trouble in requesting the HTTP status code of my localhost.
My code:
import requests
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/home', methods=['GET'])
def home():
r = requests.get(url="http://localhost:5000/home")
print(r.status_code)
return "Welcome!"
app.run()
Before adding the line for requesting status code, it works fine in my browser (Chrome) and the command prompt show something like this:
127.0.0.1 - - [19/Sep/2019 01:03:54] "GET /home HTTP/1.1" 200 -
After adding the line for requesting, it keeps loading (forever) in my browser and no response in the command prompt.
I have no idea about this problem because it did not show any error and I have read some of the solutions mentioned in other similar problems (like disabling proxy) but it seems not working for me.
Thanks!

Look at it from the point of view of the app. It gets a request for /home and routes it to home(). While servicing that request, the app makes a request for /home, which routes to home(). During the servicing of that request... and so on until some resource is exhausted.
If you intent is to prove that you can make a request to the app from within the app, target a different endpoint.

Related

Python Flask doesn't serve custom 500 template/return on IIS

I am using Flask and blueprints on IIS. My issue is that when the 500 error is triggered it loads the default IIS 500 template and not what I want.
I've tried several things and this is where I am. I have the following code
from flask import render_template,Blueprint
errorbp = Blueprint("errorbp",__name__)
#errorbp.app_errorhandler(404)
def page_not_found(e):
return "404", 404
#errorbp.app_errorhandler(500)
def internal_server_error(e):
return "500", 500
If I visit a page that does not exist, I get "404" back as intended. If I create an error on purpose, I get the following
Any suggestions as to what to do? I presume I may need to do something with IIS at this point but what? I've edited/remove the 5xx status codes/page and still nothing
What you need to do is, open the error pages module, double-click the 500 status code, set the path of your template in the file path, and IIS will send the content of the file as a custom error response.
In addition, IIS has two other ways to respond to an error: by executing an URL or by redirecting the request.

Woocomerce webhook not being recieved

I am playing around with the webhooks of WooCommerce and i have setup a hook that triggers when an item is being added to a cart.
I have a little Flask app that listens to requests and prints them out.
from flask import Flask, request, Response
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def respond():
print(request.json);
return Response(status=200)
This script is being run on the same machine as the Wordpress server.
But when i add an item to my cart no calls are being made.
Does anyone know what i am doing wrong?
I still am unable to trigger any webhook to an url that points to an service on the same machine. I tried running my endpoint in a docker container and addressing the ip address of the container. I also tried making custom dns entries in my host file. Still didnt work. Eventually fixed my problem by using ngrok.

Twilio StudioFlow ngrok 404

Hey guys I'm having a really strange issue with ngrok and Twilio StudioFlow.
For some reason, the ngrok setup using (type "ngrok http 5000" in command line) and then copy and pasting the link into StudioFlow http widgets has stopped working, when it was working fine earlier. Now, when the widgets are reached in the flow, I get these:
127.0.0.1 - - [11/Feb/2021 02:18:10] "POST /reminders HTTP/1.1" 404 -
127.0.0.1 - - [11/Feb/2021 02:18:10] "POST /week2 HTTP/1.1" 404 -
The flask routes are right (/reminders and /week2) and I am pasting them like so in the widgets (http://8b5dba64ef0c.ngrok.io/reminders) so I am really not sure why this is happening all of a sudden. Why can't twilio find my ngrok tunnel?
For context, I've tried running the flask app on different ports, but that doesn't solve the issue either. That leads me to believe theres something wrong with how to link is being read in to either twilio or my app. I haven't been able to find one though. An example of my code:
#app.route('/reminders', methods = ['POST', 'GET'])
def remmy():
# Start our empty response
resp = MessagingResponse()
if request.method == 'POST':
number = request.form['To']
print(type(number))
part = Part.query.filter_by(phone_num=number).first()
def base_reminder(num):
rem = '[#####]: Don\'t forget to complete your baseline survey to receive an incentive of $35.'
message = client.messages.create(from_='+1###########',
to=num,
body=rem)
resp = MessagingResponse()
msg = resp.message
return str(resp)
if not part.baseline:
base_reminder(part.phone_num)
return str(resp)

Route doesn't exist

I have the following code on my service and when requested the return is always 404.
#app.route('/v1/auth/service', methods=['POST'])
def verifyAuthService():
data = request.get_json()
But in the log file, the service returns 404.
127.0.0.1 - - [TIMEVALUE] "POST /v1/auth/service HTTP/1.1" 404 -
But it works when I use other route. I have checked if the route path or method name are duplicated and didn't find anything.
I request the service method with the following code:
r = requests.post("http://myservice.com:5001/v1/auth/service", json=jPayload)
Maybe was a newbie error, in my init.py file, I haven't imported auth_services.py.
The /v1/auth/service route wasn't interpreted by python so, the route was inaccessible.
Can you try building the URL with below code and match if the route is pointing to exactly same URL which you have called.
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/v1/auth/service', methods=['POST'])
def verifyAuthService():
data = request.get_json()
with app.test_request_context():
print url_for('verifyAuthService')
Hope this helps!

How do I receive Github Webhooks in Python

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

Categories

Resources