Python flask server issue - python

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

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")

Ajax POST doesn't work with Flask / IIS7.5

Because I start to go crazy I really need your help xD
I'm tying to make a simple Ajax POST, and with it I want to send JSON data to python script to save it later on server.
I'm using python 3.6.4 (anaconda3 with wfastcgi.py) for backend and Javascript (jQuery) and Flask for frontend.
Here's what I got from Chrome Dev Tools -> Network:
POST 1 is from local python server Werkzeug, POST 2 is from IIS 7.5.
I'm showing both in hope that it will help locate the problem. I only need a way to fix IIS.
I already tried :
<customHeaders> with Access-Control-Allow-Origin etc
<requestFiltering> with <add verb="POST" allowed="true" />, or <verbs allowUnlisted="true">
changing OPTIONSVerbHandler verb from OPTIONS to POST (don't ask me, found it here)
But it didn't help.
With Failed Request Tracing Rules module I was able to find this:
But I don't know what where in IIS I can change anything with FastCgi to make it work with POST.
My Ajax POST:
$.ajax({
url: "/static/scripts/saveData.py",
type: "post",
data: JSON.stringify(tableObject),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error){
console.log(error)
}
});
ps. Link to file works because when I change POST to GET I get code from saveData.py in console.log(response).
I think that you forgot to register this method in flask routs:
#app.route('/login', methods=['POST', 'GET'])
Soooo, after close to 2 days of looking in net, tying different ways to make it work, i finally found a way to send a Ajax POST.
Basically I had to change target url "/static/scripts/saveData.py" from local address to Flask url "/annotate" and this enable me to send data with POST and letter process it in views.py (my main flask view file).
$.ajax({
url: "/annotate",
type: "post",
data: JSON.stringify(tableObject),
//data: tableObject,
contentType: "application/json"
});
Now, why this work, and POST to normal .py script doesn't, I don't know.
But at least now I can work with that data.

Django python paypalrestsdk - No 'Access-Control-Allow-Origin' and ppxo_unhandled_error error

Im trying to implement paypal with Django using paypalrestsdk.
I followed the code example from the example here: https://prettyprinted.com/blog/1125955/creating-paypal-express-payments-in-flask
But there is this error:
here are my code snippets of template .html, views.py and urls.py
https://gist.github.com/axilaris/1e6e34ba5915abceb0dbd06d46baf08b
here is template code that shows the button:
<div id="paypal-button"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
var CREATE_PAYMENT_URL = 'http://127.0.0.1:8000/payment_create';
var EXECUTE_PAYMENT_URL = 'http://127.0.0.1:8000/payment_execute';
paypal.Button.render({
env: 'sandbox', // Or 'sandbox'
commit: true, // Show a 'Pay Now' button
payment: function() {
console.log("payment function")
return paypal.request.post(CREATE_PAYMENT_URL).then(function(data) {
console.log("return create payment")
return data.paymentID;
});
},
onAuthorize: function(data) {
return paypal.request.post(EXECUTE_PAYMENT_URL, {
paymentID: data.paymentID,
payerID: data.payerID
}).then(function(res) {
console.log(res.success)
// The payment is complete!
// You can now show a confirmation message to the customer
});
}
}, '#paypal-button');
</script>
What is the problem, how to fix it and what is ppxo_unhandled_error ?
Alternatively, whats the best way to implement paypal properly on Django. (I'm just not seeing any good docs on this)
Django==1.11.7
Your origin is localhost:8000 and you're trying to access a resource at 127.0.0.1:8000. The page appears the same on both localhost:8000 and 127.0.0.1:8000 because localhost (usually) translates to 127.0.0.1 on your system but your browser interprets these two destinations as different addresses. Therefore, your browser is preventing you from accessing the resource at 127.0.0.1:8000 from origin localhost:8000 because the destination resource doesn't respond with a Access-Control-Allow-Origin: http://127.0.0.1:8000 header.
I recommend changing your origin (the URL you're at in your browser) to 127.0.0.1:8000 rather than adding the header. Or changing the JavaScript around to use localhost:8000 addresses.
Access-Control-Allow-Origin (Mozilla)
The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.
This is most common problem regarding Http request when the request(localhost:8000) and Remote Address( http://127.0.0.1:8000/) for web url differ.
If you change your localhost port then also this problem will occured.
try with these two option:
1.Add this extension to your crome download extension from here
2.Get solution from this stack question

AngularJS - http request with Basic Auth (connect to FreeNAS)

Im trying to connect to the REST API of FreeNAS (http://api.freenas.org/authentication.html) within my AngularJS app. The API uses basic authentication with username and password.
In python this is a very easy thing as there is only one line of code:
requests.get('http://freenas.mydomain/api/v1.0/account/bsdusers/',auth=('root', 'freenas'))
I tried to find something for AngularJS but stumbled only over excrutiating code, e.g. How do I get basic auth working in angularjs?
Is there anything available like this:
$http({
method: 'GET',
url: 'http://freenas.mydomain/api/v1.0/account/bsdusers/',
auth: ['username':'root', 'password':'pw']
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
You need to create a function for encoding the user and password in Base64("username:password") and add Authorization header.
You can try encoding your username and password over here https://www.base64encode.org/ and see if it works. "root:freenas" being cm9vdDpmcmVlbmFz you can try the code below.
$http.defaults.headers.common['Authorization'] = 'Basic cm9vdDpmcmVlbmFz';
Once you get it working get implement the Base64 factory you posted ( How do I get basic auth working in angularjs? )
Hope it helps :)
You can try like this.
$http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"};
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('root' + ':' + 'freenas');
$http({
method: 'GET',
url: 'http://freenas.mydomain/api/v1.0/account/bsdusers/'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

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