How to use Flask development server successfully with Ajax post request? - python

I'm currently using Flasks's development server instead of using a separate one because I don't need the extra bulk. My server will not be processing many requests at once, so I feel the development server is fine enough.
What I'm Trying To Do
I have a python script that I'm trying to run with the click of a button on a web page. This web page is run on an Apache 2 web server on Ubuntu.
What I've Done
I've installed Flask and tried to post to my python script, but I always get this error:
* Serving Flask app "ResetPOE" (lazy loading)
* Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on
It always returns to my error block in my Ajax request and never to my success block. I do not get any return JSON from my Python script. I just want to know whether or not my script ran, I don't necessarily need any output from the script itself.
P.S. my Python may be incorrect, but I haven't even gotten it to recognize it yet, so that's been on the back burner for now. I'm just trying to get the post request to be successful.
ajax.js
function ajaxCall(input) {
var data = {"param" : input};
$.ajax({
url: "/cgi-bin/reset.py/request",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
dataType: 'json',
success: function(response){
console.log("success");
console.log(response);
},
error: function(xhr, status, error) {
console.log("error");
var err = xhr.responseText;
console.log(err);
}
});
}
reset.py
#!/usr/bin/python3
print("Content-type: text/html")
print ("")
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
#app.route('/')
def sendOK(environ, start_response):
status = '200 OK'
output = "Hello World!"
response_headers = [('Content-type', 'text/plain'),('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
#app.route('/request', methods=['POST'])
def processRequest():
data = request.form["param"]
# other code to do stuff with the data...
return Response(json.dumps({"status":"success"}), mimetype="application/json")
if __name__=="__main__":
app.run(debug=True, threaded=True, host="192.168.1.101")
It returns a 200 (OK) in my browser, but I'm not getting any return values, and I can tell my error block is executing and not my success block.

Related

Flask HTML/AJAX page Linking Issue

I have created a FLASK app which preforms CRUD operations on an SQL database. I had everything work a few days ago but now when using the web interface the HTML pages aren't working when clicked. For example after entering valid details and clicking login the URL now looks like:
incorrect url path
when it should redirect to
correct url path
showing in terminal
terminal
This is my folder layout
folder layout
My AJAX call to redirect to main.html
`
// Login a user
function userLogin() {
data = getLogin()
console.log(data)
$.ajax({
url:"http://127.0.0.1:5000/login",
data: JSON.stringify(data),
method:"POST",
dataType:"JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result == 1) {
window.location.replace("main.html"); // Redirect to to main.html if successful
}
},
error: function(xhr, status, error){
window.alert("Invaild username and/or password");
console.log("error "+ error + " code "+ status)
}
})
}
`
Flask Server route:
`
# Homepage route
#app.route('/')
def index():
if not 'username' in session:
return app.send_static_file('index.html')
# Login
#app.route("/login", methods = ["POST"])
def login():
account = {
"username":request.json["username"],
"password":request.json["password"]
}
return jsonify(bookmarkDAO.login(account))
`
I've tried deleting the cache, changing my folder directories around and I even tried an older version which correctly worked from my github repository but now it is even throwing the same error. I am using VS Code, could it possibly be an issue with the terminal?
You are not trailing the main.html with /
Change this
window.location.replace("main.html")
to
window.location.replace("/main.html")

Weird Axios Network Error with seemingly error-free code

I am trying to use react to get data from an API (Python, I'm hosting it on the same machine).
API Code:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/')
def all_data():
all_data = "Hello"
return jsonify({
'data':all_data,
'message':"success"
}), 200
if __name__ == "__main__":
app.run(debug=True)
React code(Didn't include the render()):
export default class HomeScreen extends Component {
constructor(props){
super(props);
this.state = {
listData:[],
url:"http://localhost:5000"
}
}
getPlanets=()=>{
console.log("Axios called")
const url = this.state.url;
console.log(url)
axios.get(url).then((response)=>{
console.log(response.data)
return this.setState({listData:response.data})
}).catch((error)=>{
console.log(error.message)
Alert.alert(error.message);
})
}
componentDidMount(){
this.getPlanets();
}
}
I'm always getting Network Error for the console.log(error.message).
I'm also getting a larger Error: "Network Error" in Error: Network Error << at e.exports (axios.js:3:7286) << at d.onerror (axios.js:3:6270) for console.log(error).
Simultaneously, I got two weird error messages in my API:
code 400, message Bad request version ('localhost\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
"▬♥☺☻☺☺ü♥♥ÆuaTÁS¾eài ¸ ²`½‼/cùCf{&*½(¨qh↓(â®z↨Ó ×D ÚÚ‼☺‼☻‼♥À+À/À,À0̨̩À‼À¶úú♫♀ l
ocalhost↨ÿ☺☺" HTTPStatus.BAD_REQUEST -
Help?
I've tried looking through a lot of websites for the problem, but they all just suggested adding the http:// prefix to my url, which I had already done. I'm also using Python for the API and not NodeJS, so I don't need to use CORS. I just couldn't find a relevant fix anywhere.

Python flask server issue

Could you please help me with Python-Flask server misunderstanding. I have some project with flask, it perfectly works on local server 127.0.0.1, but when I moved it to the Web Server (blue host), some of my script give me these errors:
Here I have jQuery, Ajax response to show a table without reloading page:
<button class="myButton" id = "Lbutton">Load</button>
<script>
$("#Lbutton").click(function(){
$.ajax({
url: "/table,
type: "get",
data: {jsdata: $( "#select option:selected" ).text()},
success: function(response) {
$("#place_for_suggestions").html(response);
},
error: function(xhr) {
// handle error
}
});
});
</script>
url: "/table, is the link for Flask function:
#FlaskApp2.route('/table')
def table():
modid = request.args.get('jsdata')
return render_template('table.html')
But finally the Server gave me error:
File does not exist: /home1/user/public_html/table
Why direct link for action, server understand like a link for a file?
So, every action to Python-Flask
<form action="/sendemail" method="post">
the Server understand like a link and give an error message !
What I'm doing wrong ?
Solved, I need to put the full path in action and route() decorator #app.route "/.../templates/table.html"
Most likely you need to add the POST method to your route definition.
#FlaskApp2.route('/table')
becomes:
#FlaskApp2.route('/table', methods=['GET', 'POST'])
Check out the documentation here:
http://flask.pocoo.org/docs/0.12/quickstart/#http-methods
Which has an example of an endpoint that accepts both GET and POST HTTP methods.
Also check out a related question: Flask example with POST

Facebook Messenger with Flask

I'm trying to get the FB messenger API working using Python's Flask, adapting the following instructions: https://developers.facebook.com/docs/messenger-platform/quickstart
So far, things have been going pretty well. I have verified my callback and am able to receive the messages I send using Messenger on my page, as in the logs in my heroku server indicate the appropriate packets of data are being received by my server. Right now I'm struggling a bit to send responses to the client messenging my app. In particular, I am not sure how to perform the following segment from the tutorial in Flask:
var token = "<page_access_token>";
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So far, I have this bit in my server-side Flask module:
#app.route('/', methods=["GET", "POST"])
def chatbot_response():
data = json.loads(req_data)
sender_id = data["entry"][0]["messaging"][0]["sender"]["id"]
url = "https://graph.facebook.com/v2.6/me/messages"
qs_value = {"access_token": TOKEN_OMITTED}
json_response = {"recipient": {"id": sender_id}, "message": "this is a test response message"}
response = ("my response text", 200, {"url": url, "qs": qs_value, "method": "POST", "json": json_response})
return response
However, running this, I find that while I can process what someone send my Page, it does not send a response back (i.e. nothing shows up in the messenger chat box). I'm new to Flask so any help would be greatly appreciated in doing the equivalent of the Javascript bit above in Flask.
Thanks!
This is the code that works for me:
data = json.loads(request.data)['entry'][0]['messaging']
for m in data:
resp_id = m['sender']['id']
resp_mess = {
'recipient': {
'id': resp_id,
},
'message': {
'text': m['message']['text'],
}
}
fb_response = requests.post(FB_MESSAGES_ENDPOINT,
params={"access_token": FB_TOKEN},
data=json.dumps(resp_mess),
headers = {'content-type': 'application/json'})
key differences:
message needs a text key for the actual response message, and you need to add the application/json content-type header.
Without the content-type header you get the The parameter recipient is required error response, and without the text key under message you get the param message must be non-empty error response.
This is the Flask example using fbmq library that works for me:
echo example :
from flask import Flask, request
from fbmq import Page
page = fbmq.Page(PAGE_ACCESS_TOKEN)
#app.route('/webhook', methods=['POST'])
def webhook():
page.handle_webhook(request.get_data(as_text=True))
return "ok"
#page.handle_message
def message_handler(event):
page.send(event.sender_id, event.message_text)
In that scenario in your tutorial, the node.js application is sending an HTTP POST request back to Facebook's servers, which then forwards the content on to the client.
So far, sounds like your Flask app is only receiving (AKA serving) HTTP requests. The reason is that that's what the Flask library is all about, and it's the only thing that Flask does.
To send an HTTP request back to Facebook, you can use any Python HTTP client library you like. There is one called urllib in the standard library, but it's a bit clunky to use... try the Requests library.
Since your request handler is delegating to an outgoing HTTP call, you need to look at the response to this sub-request also, to make sure everything went as planned.
Your handler may end up looking something like
import json
import os
from flask import app, request
# confusingly similar name, keep these straight in your head
import requests
FB_MESSAGES_ENDPOINT = "https://graph.facebook.com/v2.6/me/messages"
# good practice: don't keep secrets in files, one day you'll accidentally
# commit it and push it to github and then you'll be sad. in bash:
# $ export FB_ACCESS_TOKEN=my-secret-fb-token
FB_TOKEN = os.environ['FB_ACCESS_TOKEN']
#app.route('/', method="POST")
def chatbot_response():
data = request.json() # flasks's request object
sender_id = data["entry"][0]["messaging"][0]["sender"]["id"]
send_back_to_fb = {
"recipient": {
"id": sender_id,
},
"message": "this is a test response message"
}
# the big change: use another library to send an HTTP request back to FB
fb_response = requests.post(FB_MESSAGES_ENDPOINT,
params={"access_token": FB_TOKEN},
data=json.dumps(send_back_to_fb))
# handle the response to the subrequest you made
if not fb_response.ok:
# log some useful info for yourself, for debugging
print 'jeepers. %s: %s' % (fb_response.status_code, fb_response.text)
# always return 200 to Facebook's original POST request so they know you
# handled their request
return "OK", 200
When doing responses in Flask, you have to be careful. Simply doing a return statement won't return anything to the requester.
In your case, you might want to look at jsonify(). It will take a Python dictionary and return it to your browser as a JSON object.
from flask import jsonify
return jsonify({"url": url, "qs": qs_value, "method": "POST", "json": json_response})
If you want more control over the responses, like setting codes, take a look at make_response()

Sending Ajax request to call a python function through jquery

I am trying to send a request to call a python method in my python script.
Server Side:
I am using flask ,so the server is running on port 5000.It has a file called helloflask.py which look like
#helloflas.py
from flask import Flask
app = Flask(__name__)
#app.route("/hello",methods=['GET','POST'])
def hello():
return "Comming Here"
if __name__ == "__main__":
app.run(port=5000,debug=True)
Client Side:
Independent HTML outside of flask which is sending the ajax request.
<!--ajax call-->
<script>
function findAppartment() {
$.ajax({
url: "https://127.0.0.1:5000/hello/",
type: "get",
contentType: "application/xml; charset=utf-8",
success: function (response) {
// $('#blurg').html(response).fadeIn(1500);
}
});
}
</script>
when the request is made,I get the following error.It hits the server and gives the following error:
Error : code 400, message Bad request syntax ('\x16\x03\x01\x00\xa1\x01\x00\x00\x9d\x03\x02Q\xd8\xc0O+\x8f\xa6\x16F\x9a\x94\x90|$\x11\xd3\xd8\x15\x04$\xe4\xb4>\xc0\x0e\xe3\xa0h\xea\x07\x00\xc5\x00\x00H\xc0')
I tried many things but things don't seem to be working.Could any one help???Any help is highly appreciated.

Categories