Trying flask functions but get error that url is not valid - python

I wish to show my data in a webpage by using flask. (Trying to learn it)
from flask import Flask, jsonify, make_response
from flask_cors import CORS
api = Flask(__name__)
CORS(api)
api.config['JSON_AS_ASCII'] = False
api.config["JSON_SORT_KEYS"] = False
#api.route('/token',methods=["POST"])
def get_token(self):
data = {
"type": "testing",
}
response1 = make_response(jsonify(data))
return response1
if __name__ == "__main__":
api.run(port=11111)
current output when try http://127.0.0.1:11111/ on google chrome:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I also tried with /token:
Method Not Allowed
The method is not allowed for the requested URL.

you need to go to http://127.0.0.1:11111/token, if you want to go to http://127.0.0.1:11111/ you need to define a function with route #api.route('/',methods=["POST"])
Also a browser makes GET requests via URL unless explicitly defined, change it to get via #api.route('/',methods=["GET"])

Your route is /token, so you need to go to http://127.0.0.1:11111/token.

POST requests cannot be directly viewed in browser. Try some rest API client like Postman to test your POST request.
Alternatively, if you want to test if the API just works, change the POST method to GET. Then if you visit http://127.0.0.1:11111/token, you can see the response. Also you don't need 'self' argument to your method.

You restrict your app.route to only POST. If you want to enter your page from url you have to specify GET as well.
Read about http requests
from flask import Flask, jsonify, make_response
from flask_cors import CORS
api = Flask(__name__)
CORS(api)
api.config['JSON_AS_ASCII'] = False
api.config["JSON_SORT_KEYS"] = False
#api.route('/token',methods=["GET", "POST"])
def get_token(self):
data = {
"type": "testing",
}
response1 = make_response(jsonify(data))
return response1
if __name__ == "__main__":
api.run(port=11111)

Related

How to make rest API that responds to post(data=data,header=header) with python and flask

I am trying to make a rest API in python.flask and I want it to be responsive to python.requests.post(data=data,header=header). But every tutorial and website only shows me Postman and
An API that responds to python.requests.post(PARAMS=data,header=header) but "PARAMS" does not work for my case. I've tried using python.flask.request.get_json(), I've tried using python.flask.Resource, I've tried using another one here:-
from flask import Flask
from flask_restful import Resource, Api, reqparse
from json import loads as dictionary
from flask import request as req
app = Flask(__name__)
api = Api(app)
#app.route('/test', methods=['POST'])
def post(username,token,url):
# gotit=dictionary(gotit)
k = '{"name":'+username+',"password":'+token+',"link":'+url+'}'
print(k)
return k
if __name__ == '__main__':
app.run()#debug=True)
But all in vain. Please help me make an API that responds to this:- python.requests.post(data=data,header=header). And also help with the header thing.
Python.v3.8
Here's your code but with some modification:
Server Code:
from flask import Flask, jsonify, request
import requests
import json
app = Flask(__name__)
#app.route('/test', methods=['POST'])
def post():
# you will get that data in request.data you can simplify/jsonfiy
text = str(request.data)
t = request.data
return t
if __name__ == "__main__":
app.run(debug=True)
python.requests Code:
import requests
header = {
"Content-Type":"text/plain"
}
data = {
"username":"myName",
"password":"myPass",
"url":"myWeb"
}
d = requests.post(url='http://127.0.0.1:5000/test', data=data, headers=header)
#
print(d.content)
Response from server something like this:
response Screenshot
I'm Using Python 3.9.1
Hope it will help You:)

Flask - Pass back response of inner request

I looked at some of the similar suggested SO questions, but they weren't quite what I was looking for:
I have a Flask server with a POST route that calls another server. I want Flask to return the response from that request as-is.
import os
import requests
from flask import Flask, request, jsonify, make_response, Response
#app.route('/stuff', methods=['POST'])
def get_stuff():
resp = requests.post(...)
return resp
app.run(host='0.0.0.0', port=9999)
I've tried the following but each returns an error:
return jsonify(resp)
return ( resp.raw.read(), resp.status_code, resp.headers.items() )
return Response(json.dumps(resp), status=resp.status_code, mimetype='application/json')
I just want it to pass back what it got
Flask route functions should only return a string, you need a method to convert it and each of the attempts you made probably fell short in one way or another to do so.
Post the error messages, they may clue in how close you are to accomplishing the rerouting of the post response.

How can i build a proper restful response API by python flask for parameters

I'm studing about RESFful API with python.
I want to build a my restful api server,
but i have a problem,
i don't know how my api server returns proper data by reqeust each parameters
(request code sample)
the request code wants to get the information about 'item' : 'sword'
import requests
import json
url = "https://theURL"
querystring={"item":"sword"}
response = requests.request("GET", url, params=querystring)
print (response.json())
(API server response code sample, by flask python)
from flask import Flask, url_for
from flask_restful import Resource, Api, abort, reqparse
app = Flask(__name__)
api = Api(app)
TODOS = {
"version":"2.0",
"resultCode":"OK",
"output":{
{
"item" :"sword"
"price": 300,
"damage": 20,
},
{
"item" :"gun"
"price": 500,
"damage": 30,
},
},
}
class Todo(Resource):
def post(self):
return TODOS
api.add_resource(Todo, '/item.price')
if __name__ == "__main__":
app.run(debug=True, host ="192.168.0.8", port = 8080)
So i want to know how i use a code in response api server for returning 'item price' data by reqeusted parameters 'item : sword'
I just want to get the selected parameter's item price and damage information.
I thought it might be very easy, i'm tried to search the example but i couldn't find proper sample code.
I'm not a Flask-expert, but this helps setting up and running a minimalistic Flask-server. Then, this explains how to return json-formatted data from your server, and finally how to request and interpret the json-response can be found here. Summarized below:
Server returning a json-formatted data:
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def hello():
return "Hello, World!"
#app.route('/request_sword')
def grant_sword():
return jsonify({"sword": {"name":"Excalibur","price":"stack overflow"}})
Client requesting json-formatted data:
import json
import urllib.request
url = "http://127.0.0.1:5000/request_sword" ## My local host flask server
data = urllib.request.urlopen(url)
response = json.loads(data.read())
print(response)
That's all really. You may also just enter the url in your browser, which will correctly read the json-data:

Is it possible to make POST request in Flask?

There is a need to make POST request from server side in Flask.
Let's imagine that we have:
#app.route("/test", methods=["POST"])
def test():
test = request.form["test"]
return "TEST: %s" % test
#app.route("/index")
def index():
# Is there something_like_this method in Flask to perform the POST request?
return something_like_this("/test", { "test" : "My Test Data" })
I haven't found anything specific in Flask documentation. Some say urllib2.urlopen is the issue but I failed to combine Flask and urlopen. Is it really possible?
For the record, here's general code to make a POST request from Python:
#make a POST request
import requests
dictToSend = {'question':'what is the answer?'}
res = requests.post('http://localhost:5000/tests/endpoint', json=dictToSend)
print 'response from server:',res.text
dictFromServer = res.json()
Notice that we are passing in a Python dict using the json= option. This conveniently tells the requests library to do two things:
serialize the dict to JSON
write the correct MIME type ('application/json') in the HTTP header
And here's a Flask application that will receive and respond to that POST request:
#handle a POST request
from flask import Flask, render_template, request, url_for, jsonify
app = Flask(__name__)
#app.route('/tests/endpoint', methods=['POST'])
def my_test_endpoint():
input_json = request.get_json(force=True)
# force=True, above, is necessary if another developer
# forgot to set the MIME type to 'application/json'
print 'data from client:', input_json
dictToReturn = {'answer':42}
return jsonify(dictToReturn)
if __name__ == '__main__':
app.run(debug=True)
Yes, to make a POST request you can use urllib, see the documentation.
I would however recommend to use the requests module instead.
EDIT:
I suggest you refactor your code to extract the common functionality:
#app.route("/test", methods=["POST"])
def test():
return _test(request.form["test"])
#app.route("/index")
def index():
return _test("My Test Data")
def _test(argument):
return "TEST: %s" % argument

a little bit of python help

i need a little help here, since i am new to python, i am trying to do a nice app that can tell me if my website is down or not, then send it to twitter.
class Tweet(webapp.RequestHandler):
def get(self):
import oauth
client = oauth.TwitterClient(TWITTER_CONSUMER_KEY,
TWITTER_CONSUMER_SECRET,
None
)
webstatus = {"status": "this is where the site status need's to be",
"lat": 44.42765100,
"long":26.103172
}
client.make_request('http://twitter.com/statuses/update.json',
token=TWITTER_ACCESS_TOKEN,
secret=TWITTER_ACCESS_TOKEN_SECRET,
additional_params=webstatus,
protected=True,
method='POST'
)
self.response.out.write(webstatus)
def main():
application = webapp.WSGIApplication([('/', Tweet)])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
now the check website part is missing, so i am extremely new to python and i need a little bit of help
any idea of a function/class that can check a specific url and the answer/error code can be send to twitter using the upper script
and i need a little bit of help at implementing url check in the script above, this is my first time interacting with python.
if you are wondering, upper class uses https://github.com/mikeknapp/AppEngine-OAuth-Library lib
cheers
PS: the url check functionality need's to be based on urlfetch class, more safe for google appengine
You could use Google App Engine URL Fetch API.
The fetch() function returns a Response object containing the HTTP status_code.
Just fetch the url and check the status with something like this:
from google.appengine.api import urlfetch
def is_down(url):
result = urlfetch.fetch(url, method = urlfetch.HEAD)
return result.status_code != 200
Checking if a website exists:
import httplib
from httplib import HTTP
from urlparse import urlparse
def checkUrl(url):
p = urlparse(url)
h = HTTP(p[1])
h.putrequest('HEAD', p[2])
h.endheaders()
return h.getreply()[0] == httplib.OK
We only get the header of a given URL and check the response code of the web server.
Update: The last line is modified according to the remark of Daenyth.

Categories