Get and Post data in Flask request - post

Hello and thanks in advance for any help.
I am trying to set up a ReactJS & Flask Web App, but i am having trouble getting the data into Flask, i am using Insomnia to test send the data to Flask, and the POST request returns code 200, but i keep on getting the error on the printscreen below, UnboundLocalError: local variable 'text' referenced before assignment. The string is not passed to the TTS (text-to-speech) class for processing, when i use direct assignment for the strings on the comented code bellow the imports works fine.
I have tried to send the data with JSON, now i am trying with form format, it returns the same error.
Can you help me, please, and take a look at my code ?
from flask import Flask, render_template, request
import speak
# text = "AI AI minha machadinha !!"
# lang = "pt"
app = Flask(__name__, static_folder="../static/dist", template_folder="../static")
#app.route("/", methods=["GET","POST"])
def index():
return render_template("index.html")
#app.route("/hello", methods=["GET","POST"])
def hello():
if request.method == "POST":
text = request.form["text"]
lang = request.form["lang"]
print("passou")
return speak.get_speak(text,lang)
if __name__ == "__main__":
app.run()
Insomnia code 200 message
error on console log

Try this below :
#app.route("/hello", methods=["GET","POST"])
def hello():
text = ''
if request.method == "POST":
text = request.form["text"]
lang = request.form["lang"]
print("passou")
return speak.get_speak(text,lang)
This is beacause your text is defined inside if condition and your return is outside the if condition. You need to define it above the if and give it a default value.

Related

cannot authorize using Rest-Assured

400 error cannot understand where is mistake in code
I used Rest-assured documentation
https://www.toolsqa.com/rest-assured/post-request-using-rest-assured/
Please help with this question
package forth;
import org.apache.log4j.BasicConfigurator;
import org.testng.annotations.Test;
import org.testng.Assert;
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
import io.restassured.response.Response;
import org.json.simple.JSONObject;
public class zero {
#Test
public void RegistrationSuccessful()
{
BasicConfigurator.configure();
RestAssured.baseURI ="url";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("useremail", "my login");
requestParams.put("api_token", "my token");
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/rest/auth/1/session");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "201");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");
}
}
First of all, always try opening the end point url in new tab of browser, if it doesn't give any error then, it is an indication that we can use it. If browser displays something like "This site can't be reached", then it is not a valid end point or server is not up and running for respective end point.
In case of toolsqa website, in starting few pages endpoints are not working. I sent a message to Virender to look into this issue, but unfortunately no response.
I suggest you to learn rest assured from makeseleniumeasy website as per my personal experience.
Its very important to check if the api requires form params or body params.
form-params are intended to be used with content-type "application/x-www-form-urlencoded" (a form)
body-params are intended to use for parameters which are also going to be located in the body with other content-types (application/json)

Twilio - Quick question (Unable to update record)

hope you are doing it right these days.
To summarize my problem, I think this is not working becuase I am using a free Twilio account instead of a paid one. But that's just my beginner theory. Now, the issue:
I have tried an official Twilio tutorial (https://www.twilio.com/blog/automating-ngrok-python-twilio-applications-pyngrok, I shared the link in case someone finds it interesting or needs it), which allows us to automate SMS webhook (sms_url) configuration by using Client (twilio) and pyngrok (ngrok).
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url + '/bot')
I can't explain all the things that I tried in the last 4 days, with no success. I keep getting the same error:
client.incoming_phone_numbers.list(phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(sms_url=url + '/bot')
IndexError: list index out of range
Something is not working with the list, it comes empty, although environment variables are working properly. I will work with just one phone_number, so there no need for list, indeed, so I started to change that line to avoid different errors and ended up with this:
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers("my_number").update(sms_url=str(url) + '/bot')
Then I got the final error that I can't solve by my self:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py", line 442, in update
payload = self._version.update(method='POST', uri=self._uri, data=data, )
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/base/version.py", line 106, in update
raise self.exception(method, uri, response, 'Unable to update record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json
Twilio returned the following information:
Unable to update record: The requested resource /2010-04-01/Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I tried all different phone numbers combinations/formats: nothing works.
Thanks for your time reading all this!
Looks like something changed since the blog was written or there was a mistake.
Try the below:
The only difference is adding .public_url to the url object. Also allowed a GET to /bot for testing.
from dotenv import load_dotenv
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
app = Flask(__name__)
#app.route('/bot', methods=['POST','GET'])
def bot():
user = request.values.get('From', '')
resp = MessagingResponse()
resp.message(f'Hello, {user}, thank you for your message!')
return str(resp)
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print('This is',url)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url.public_url + '/bot')
if __name__ == '__main__':
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
start_ngrok()
app.run(debug=True)

Why Am I Getting An Error When Connecting To Google Search Console API Via Flask Dance?

Im creating a flask app that retrieves data from Google Search Console API.
However I'm having hard times implementing Google OAuth with Flask-Dance.
I am getting the following error:
Here is my code:
from flask import Flask, render_template, request, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
import os
def create_app(config_name):
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
print(config_name)
blueprint = make_google_blueprint(
client_id={MY CLIENT ID},
client_secret={MY SECRET},
scope=["profile", "email"])
app = Flask(__name__)
app.config.from_object(config[config_name])
google_bp = make_google_blueprint(scope=["profile","email","https://www.googleapis.com/auth/webmasters"])
#app.route("/search")
def search():
if not google.authorized:
return redirect(url_for("google.login"))
request = {
'startDate': '2019-01-01',
'endDate': '2019-01-31','dimensions': ['query']}
resp = google.post("/webmasters/v3/sites/https%3A%2F%2Fwww.mysite.com/searchAnalytics/query", json=request)
amt=resp['rows'][0]['clicks']
return '<h1>'+amt+'</h1>'
return app
I have also set up the application in Google Developers Console following the below steps, outlined here:
https://flask-dance.readthedocs.io/en/v0.8.0/quickstarts/google.html
Any ideas what might be the issue?
Many thanks in advance
From the screenshot, client_id=None, it looks like you have some misconfiguration. In your code, there are two make_google_blueprint.
You can review your code again to fix this problem.

Cherrypy respond to unmounted or incorrect url

I have been confused by the following:
I have a class TestLink mounted to the url /testlink
class TestLink(object):
exposed = True
#cherrypy.expose
#cherrypy.tools.accept(media='text/plain')
def GET(self, var=None, **params):
return "data:1,2\\nzelta:3,4"
if __name__ == '__main__':
app = cherrypy.tree.mount(
TestLink(), '/testlink',
"test.config"
)
And I use the Cherrypy rest dispatcher in my "test.config" file:
request.dispatch = cherrypy.dispatch.MethodDispatcher()
And when I hit start the server and hit the url "http://127.0.0.1:8080/testlink", I get the result. However, I also get result if I hit the url http://127.0.0.1:8080/testlink/x or "http://127.0.0.1:8080/testlink/anything_string". Why does this happen, shouldn't only the url "http://127.0.0.1:8080/testlink" return data?
Given your code example, if you try to access http://127.0.0.1:8080/testlink/foo/bar cherrypy will respond with 404 Not Found. This is because MethodDispatcher is interpreting 'foo' as value of the parameter 'var', as you specified in the signature of GET().
Here's a modified working version of your example:
import cherrypy
config = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.trailing_slash.on': False,
}
}
class TestLink(object):
exposed = True
## not necessary, you want to use MethodDispatcher. See docs.
##cherrypy.expose
#cherrypy.tools.accept(media='text/plain')
def GET(self, var=None, **params):
print var, params
return "data:1,2\\nzelta:3,4"
if __name__ == '__main__':
app = cherrypy.tree.mount(TestLink(), '/testlink', config)
cherrypy.engine.start()
cherrypy.engine.block()
Now try http://127.0.0.1:8080/testlink/foo, it will print
foo {}
whereas hitting http://127.0.0.1:8080/testlink/foo/bar will lead to 404.
See the docs https://cherrypy.readthedocs.org/en/3.3.0/refman/_cpdispatch.html, or of course you could investigate the code in the module cherrypy/_cpdispatch.py yourself.

POST request with data

This might be a noob question but i've been fiddling with it for hours now and wasn't able to find the solution.
I would like to send a POST request with form data using grails,
in jQuery this following 1 liner works as I wish:
$.post('<SOME SERVER URI>', {param1: 'p1'}, function(data) {console.log(data);})
but the following Grails code doesn't:
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.POST
import groovyx.net.http.HTTPBuilder
...
def http = new HTTPBuilder(<SERVER BASE URI>)
http.request(POST, JSON) {
uri.path = <REST OF URI>
uri.query = [param1: 'p1']
response.success = { resp, json ->
println 'success'
}
}
I think it has something to do with the data being sent, as the request leaves but fails (facebook graph is the base uri...)
the jquery code sends the data as form data, but i'm not sure thats the problem
Thanks!
It seems that facebook are really stickt on the params, and by sending 2 extra params facebook would not process the request, and simply return 400.
Thanks so much!

Resources