I have created 2 apps in FLASK, one app will issue a GET request and pull the data, 2nd app will take that data from app 1 and issue a POST request to push data into other system.
APP1.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
#app.route('/pushdata', methods=['GET', 'POST'])
def testfn():
# POST request
if request.method == 'POST':
print(request.get_json()) # parse as JSON
req = request.get_json()
print(type(req))
print(req)
return 'Success!! Reached Flask', 200
# main driver function
if __name__ == '__main__':
app.run(debug=True)
APP2.py
from flask import Flask,jsonify,request,make_response,url_for,redirect
import requests, json
app = Flask(__name__)
url = 'http://xx.xx.xx.xxx:<PORT>/lemte/7/rest/tenten/'
json_data = **<JSON DATA received from APP1....................>**
headers = {'content-type': 'application/json'}
res = requests.post(url, headers=headers, auth=('XXXXX', 'YYYYY'), data=json.dumps(json_data))
print ('response from server:',res.text)
dictFromServer = res.json()
if __name__ == '__main__':
app.run(host='localhost',debug=False, use_reloader=True)
How can I achieve this? searched a lot, but unable to find any hints/suggestions.
Perhaps you could try through a POST request from APP1 to APP2 or through sockets where APP1 would be the server and APP2 the client.
Edit:
This might help:
communication-between-two-python-scripts and
communication-between-two-python-scripts
They both have the same title but different answers
this solves your problem in order to let 2 flask app talk to each other :
In APP1.py:
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
#app.route('/lemte/7/rest/tenten', methods=['GET', 'POST'])
def testfn():
if request.method == 'POST':
print(request.get_json()) # parse as JSON
req = request.get_json()
print(type(req))
print(req)
return jsonify({"message":"success!! readched flask"}),200
# return 'Success!! Reached Flask', 200
if __name__ == '__main__':
app.run(debug=True,port=5201)
In APP2.py:
from flask import Flask,jsonify,request,make_response,url_for,redirect
import requests, json
app = Flask(__name__)
url = 'http://localhost:5201/lemte/7/rest/tenten'
json_data = {"test":"hello"}
headers = {'content-type': 'application/json'}
res = requests.post(url, headers=headers, auth=('XXXXX', 'YYYYY'),
data=json.dumps(json_data))
print ('response from server:',res.text)
dictFromServer = res.json()
if __name__ == '__main__':
app.run(host='localhost',debug=False, use_reloader=True,port=5200)
You did not not specified any error here
I assume the error is that you tried to run both in same port which is not possible
You can run each in different ports by specifying port in app.run
example:
app1
from flask import Flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(host="localhost", port=5000)
app2
from flask import Flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(host="localhost", port=5001)
You can use python app1.py and python app2.py in two different terminals to run the servers
Related
So, i am trying to send an audiofile and text as arguments to a flask api, it works fine when i send them through postman but i get a bad request error when i post it through python code.
Here is my python code:
import requests
import json
url= 'http://192.168.100.14:8000/v1/translate'
with open('/home/faizi/ai-chatbot-with-voice-driven-facial-animation/01_smalltalk_bot/game.wav', 'rb') as file:
files = {'input_file': file}
d = {"text":"hello, my name is faizan"}
req = requests.post(url, files=files, json=d)
print(req.status_code)
print(req.text)
And here is my flask api:
from flask import Flask
from flask_cors import cross_origin
from flask import Blueprint, request, Response
import json
from Voice_Cloning_Module import demo_cli
from flask import send_file
app = Flask("foo")
#app.route('/v1/translate', methods=['POST', 'OPTIONS'])
#cross_origin()
def translate_mbart():
data = request.get_json()
audio_file = request.files['input_file']
audio_file.save("./bufferaudiofile/"+audio_file.filename)
text = request.form['text']
returnedfile = demo_cli.clone(text,"./bufferaudiofile/"+audio_file.filename)
path_to_clonefile = returnedfile
return send_file(
path_to_clonefile,
mimetype="audio/wav",
as_attachment=True,
attachment_filename="test.wav")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
I am getting 400 bad request error and i dont understand what could be the issue, it works fine in postman
I was able to successfully send a wav file using the following code. I suggest stripping it back to bare bones and focussing on receiving the file to make sure nothing else is causing the issue.
For the API:
from flask import Flask
from flask import request
import json
app = Flask(__name__)
#app.route('/main', methods=['POST', 'OPTIONS'])
def main():
file = request.files['file']
print(file)
return { "ok": True }
if __name__ == '__main__':
app.run(host = 'localhost', port = 8000)
And for the request:
import requests
import json
url = 'http://localhost:8000/main'
with open('test_file.wav', 'rb') as wav:
files = { "file": wav }
d = { "body" : "Foo Bar" }
req = requests.post(url, files=files, json=d)
print(req.status_code)
print(req.text)
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:)
I am using Flask and fbmq, documentation here:https://github.com/conbus/fbmq,
for building a messenger bot.I have the correct access and verification codes but I am still getting a 404 NOT FOUND error. Here is my server.pt code:
from flask import Flask, request
from fbmq import Page
app = Flask(__name__)
page = Page()
#app.route('/webhook', methods=['GET'])
def validate():
if request.args.get('hub.mode', '') == 'subscribe' and \
request.args.get('hub.verify_token', '') == '':
print("Validating webhook")
return request.args.get('hub.challenge', '')
else:
return 'Failed validation. Make sure the validation tokens match.'
#app.route('/webhook', methods=['POST'])
def webhook():
payload = request.get_data(as_text=True)
print(payload)
page.handle_webhook(payload)
return "ok"
if __name__ == '__main__':
app.run( port=5000, debug=True, threaded=True)
I abandoned this project, but this was probably because I didn't add /webhook/ after my ngrok url.(I know because this solved the the problem in another project)
I'm currently testing Google Search Console API and Flask Dance to do the oauth stuff.
It works great for getting the /sites, but i get an
ValueError: View function did not return a response
if i try to query searchAnalytics with /search
According to https://developers.google.com/webmaster-tools/search-console-api-original/v3/searchanalytics/query#try-it it must be POST + additonal data. e.g.:
json={'startDate':'2017-11-01','endDate':'2017-12-01'}
In https://developers.google.com/oauthplayground/ it works like this but with flask dance sadly not. any ideas?
import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID")
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET")
google_bp = make_google_blueprint(scope=["profile", "email", "https://www.googleapis.com/auth/webmasters"])
app.register_blueprint(google_bp, url_prefix="/login")
#app.route("/")
def index():
return "BlA BLA"
#app.route("/sites")
def sites():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/webmasters/v3/sites")
siteEntry = resp.json()["siteEntry"]
result = ""
for site in siteEntry:
result = result + site["siteUrl"] + "</br>"
return result
#app.route("/search")
def search():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.post("/webmasters/v3/sites/https%3A%2F%2Fzrce.eu/searchAnalytics/query", json={'startDate':'2017-11-01','endDate':'2017-12-01'})
print(resp)
if __name__ == "__main__":
app.run()
All API routes should always return something even if its an empty response.
Simply return a response, it can be "" or resp.
Howdie do,
I'm just running a simple flask API call.
The flask API will take a XML request in and then parse the XML and print it to the terminal screen.
However, everytime I do this, I'm receiving
The method is not allowed for the requested URL
The Flask script is:
__author__ = 'Jeremy'
from flask import Flask
from flask import request
import xmltodict
app = Flask(__name__)
#app.route('/', methods=['POST'])
def parsexml():
xmlrequest = xmltodict.parse(request.data)
print xmlrequest
if __name__ == '__main__':
app.run()
The script that sends the XML is:
__author__ = 'Jeremy'
import requests
xml = """
<dtc:GetShipmentUpdates>
<dtc:GetShipmentUpdatesRequest>
<dtc:SearchStartTime>2015-07-12T12:00:00</dtc:SearchStartTime>
<dtc:SearchEndTime>2015-07-12T12:30:00</dtc:SearchEndTime>
</dtc:GetShipmentUpdatesRequest>
</dtc:GetShipmentUpdates> """
headers = {'Content-Type': 'application/xml'}
r = requests.post('http://127.0.0.1:5000/', data=xml, headers=headers)
print r.content
Does anyone know why this is happening and if so, how can I send a POST request to my flask application running on 127.0.0.1:5000
You aren't returning anything from parsexml. Try returning some content:
#app.route('/', methods=['POST'])
def parsexml():
xmlrequest = xmltodict.parse(request.data)
print xmlrequest
return "Thanks for the data!"
Howdie do,
You can't send POST requests to /
So I changed it to go to the following:
__author__ = 'Jeremy'
from flask import Flask
from flask import request
import xmltodict
app = Flask(__name__)
#app.route('/')
def say_hello():
return "Say goodbye Jeremy"
#app.route('/api', methods=['POST'])
def parsexml():
xmlrequest = xmltodict.parse(request.data)
return xmlrequest
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int("80"))
Work now