My appliaction need to save the particular static image accessed count in datastore.
Here is the Current Code:
Image URL: http://my_app.appspot.com/static_image
class Image_Display(webapp2.RequestHandler):
def get(self):
...........
// Increment the count & save it in datastore
self.redirect("/images/static.gif")
app = webapp2.WSGIApplication([('/static_image', Image_Display)], debug=False)
Instead of self.redirect("/images/static.gif"), Is the better way to do this ?
In this case, Always have 2 request for each image request.
"GET /static_image HTTP/1.1" 302 -
"GET /images/static.gif HTTP/1.1" 200 1453
For a redirect you use two requests. You can also read the image from the static project path in a single request:
class Image_Display(webapp2.RequestHandler):
def get(self):
...........
// Increment the count & save it in datastore
path = os.path.join(os.path.dirname(__file__), 'images', 'static.gif')
self.response.headers[b'Content-Type'] = mimetypes.guess_type('static.gif')[0]
self.response.write(file(path, 'rb').read())
Related
I'm trying to create a simple microservice structure on my Django projecjt: so when a certain Django view is called, this view will send a JSON post request to a Flask microservice containing some user's data; the Flask microservice should receive the request, take that user's data and send back to Django some additional data using Requests again, so that my Django view can receive that data and perform some operations, such as showing it to the user.
Right now i'm just sending some dummy data, to test if this whole system ( Django > request to Flask > Flask > Request to Django) works, but i'm having some problems.
To debug my code, i'm trying to just print the received data. Here is my view:
def myView(request):
mydict = {}
# The request is sent to my external Python script..
req = requests.post('http://127.0.0.1:5000/', json={"one": 1}) # Some dummy data
# .. Once the external script sends back a request with data, this should handle it
if request.method == 'POST':
# The data is inside this variable
data = request.POST
for key in data.items():
if float(key[1]) > 0:
mydict.update({key[0]: key[1]})
print(mydict) #FIRST PRINT STATEMENT
print(mydict) #SECOND PRINT STATEMENT
response = HttpResponse(get_token(request))
return JsonResponse(mydict) #RETURNS "{}"
And here is how my Flask app sends data (once it receives the POST request from the Django view) using the Python-Requests library:
#app.route("/", methods=["GET","POST"])
def test():
# After the request from the VIEW is received, a request containing some random json data
# is sent to Django
url = 'http://127.0.0.1:8000/myView/'
client = requests.session()
# We need to get the CSRF token, in order for the request to be taken by Django
csrftoken = requests.get(url).cookies['csrftoken']
data = {"two": 2}
header = {'X-CSRFToken': csrftoken}
cookies = {'csrftoken': csrftoken}
resp = requests.post(url, data=data, headers=header, cookies=cookies)
# Let's seend the request to Django
return f"Test!"
Here is what's wrong with my code:
METHOD: POST
{'two': 2}
[10/Jan/2020 10:41:37] "POST /myView/ HTTP/1.1" 200 320
{}
[10/Jan/2020 10:41:37] "GET /myView/ HTTP/1.1" 200 2
Here is what's wrong:
Why does the first print statement return the correct data and why doesn't the second print? And why does return JsonResponse return an empty dictionary?
I tried to add print('METHOD: ', request.method) in the first lines of the view, here is what happened:
METHOD: GET
METHOD: GET
[10/Jan/2020 10:46:22] "GET /myView/ HTTP/1.1" 200 2
METHOD: POST
[10/Jan/2020 10:46:26] "POST /myView/ HTTP/1.1" 200 320
[10/Jan/2020 10:46:26] "GET /myView/ HTTP/1.1" 200 2
You're flask view can be simplified to just return the required data
#app.route("/", methods=["GET","POST"])
def test():
return {"two": 2}
Then you can use the data in the Django view after you have made the request to flask
response = requests.post('http://127.0.0.1:5000/', json={"one": 1})
print(response.json()) # This should contain the returned data
I'm writing a simple Flask application in which I want to send some data from the front-end to the Flask app, have it perform some operations, and return new data to the front-end for display. I have made similar applications before, and by returning the POST response object, instead of render_template(), I'm able to simply return the data and do what I want with it on the front-end. However, this time I'm having problems.
I make a POST request from the Jquery in the front-end. Everything seems to work fine, I can see the data being returned in the browser console, except the page reloads before I can display the new data. It reloads to http://xxx.x.x.x:5000/?.
I can see the get request for /? in the Flask console. I'd like to know why it is doing this, and how I can get it to stop.
(I've found this difficult to research because most search engines will silently ignore any question marks in a query.)
Flask app:
import json
from flask import Flask, Response, render_template, request
from src.simple_lookup import analogy_lookup
app = Flask(__name__)
app.config['DEBUG'] = True
#app.route('/')
def hello_world():
return render_template('index.html', results=['a', 'b'])
#app.route('/get_words_simple', methods=['POST'])
def get_words_simple():
print('request.form:', request.form.keys)
data = analogy_lookup(request.form['keyword'], request.form['base'], request.form['goal'])
resp = Response(json.dumps(data), status=200, mimetype='application/json')
print('data:', data)
print('resp:', resp)
return resp
if __name__ == "__main__":
app.run()
Jquery:
$.post('get_words_simple?', data, function(json, status) {
console.log('response:', json);
if (json.hasOwnProperty('error')) {
$('.results').append('<p>' + json.error);
return;
}
var words = json.words;
$.each(words, function(i, text) {
var p = $("<p>");
p.append(text);
$('.results').append(p);
});
});
Flask console:
127.0.0.1 - - [27/Dec/2018 11:12:21] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2018 11:12:21] "GET /static/js/main.js HTTP/1.1" 200 -
request.form: <bound method MultiDict.keys of ImmutableMultiDict([('keyword', ''), ('base', ''), ('goal', '')])>
127.0.0.1 - - [27/Dec/2018 11:12:23] "GET /? HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2018 11:12:23] "GET /static/js/main.js HTTP/1.1" 200 -
data: ['obtuvo', 'takata', 'stadshypotek', 'kriwet', 'shafiee', 'martorell', 'collum', '29,400', 'muteesa', 'patzek']
resp: <Response 111 bytes [200 OK]>
127.0.0.1 - - [27/Dec/2018 11:12:23] "POST /get_words_simple? HTTP/1.1" 200 -
Problem was that Bootstrap overrides type="submit" button functionality if it's in a form group. So my Jquery was doing everything right, but something about the html of the button was screwing everything up and trying to make a post request in a different way
Hi everyone I'm new with python bottle and I'm developing an API to be consumed by Angularjs. When I try to use the endpoints it shows me the next error in the browser console:
XMLHttpRequest cannot load build.my.domain.com:8001/api/ldap/authenticate. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin build.my.domain.com:8000' is therefore not allowed access.
I currently enabled the bottle CORS:
the decorator
def enable_cors(fn):
def _enable_cors(*args, **kwargs):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
if request.method != 'OPTIONS':
# actual request; reply with the actual response
return fn(*args, **kwargs)
return _enable_cors
Even after make the call the back shows me the next log:
http://build.my.domain.com:8000
10.30.16.70 - - [05/Mar/2016 12:58:07] "OPTIONS /api/ldap/authenticate HTTP/1.1" 200 0
http://build.my.domaincom:8000
10.30.16.70 - - [05/Mar/2016 12:58:07] "OPTIONS /api/ldap/authenticate HTTP/1.1" 200 0
but I stills the errors appears
XMLHttpRequest cannot load build.my.domain.com:8001/api/ldap/authenticate. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin build.my.domain.com:8000' is therefore not allowed access.
I am experimenting in Bottle/MongoDB extending the Blog Engine from one of the MongoDB University Courses.
I have added a header & footer template and added some simple JS, CSS and an image. These work fine on all the templates other than show_post view. The way that it seems to be set up is that the value passed in to the function includes the static files (css, js & png) as well as the URL variable for the blog post itself.
The values from the python console are:
about to query on permalink = TLxrBfyxTZjqOKqxgnUP
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/TLxrBfyxTZjqOKqxgnUP HTTP/1.1" 200 37682
about to query on permalink = style.css
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/style.css HTTP/1.1" 303 0
about to query on permalink = blog.js
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/blog.js HTTP/1.1" 303 0
about to query on permalink = BL_logo.png
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/BL_logo.png HTTP/1.1" 303 0
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
The code in question is:
# Displays a particular blog post
#bottle.get("/post/<permalink>")
def show_post(permalink="notfound"):
cookie = bottle.request.get_cookie("session")
username = sessions.get_username(cookie)
permalink = cgi.escape(permalink)
print "about to query on permalink = ", permalink
post = posts.get_post_by_permalink(permalink)
if post is None:
bottle.redirect("/post_not_found")
# init comment form fields for additional comment
comment = {'name': "", 'body': "", 'email': ""}
return bottle.template("entry_template", dict(post=post, username=username, errors="", comment=comment))
How can I prevent the function being called at all if the 'permalink' is a file rather than a value from a query string?
Thanks,
Mark
ANSWER
With many thanks to Ron's answer below for pointing me in the right direction.
My error was down to the path to the static files being incorrect. I made the path dynamic by importing os and then changed the root value to os.path.join(os.getcwd(), 'static/js') and made the filepaths in my header.tpl absolute, e.g."/style.css".
#bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
rootPath=os.path.join(os.getcwd(), 'static/css')
return bottle.static_file(filename, root=rootPath)
Because you've placed your assets under /post, they're conflicting with your /post/<permalink> route.
Typically, you would serve your assets (css, js, png) from their own directory; something like /static/css/foo.css. That's what I'd recommend here.
Something along the lines of this:
#bottle.get("/post/<permalink>")
def show_post(permalink="notfound"):
# code to generate a post page goes here
#bottle.get("/static/<file_name:path>"):
def static_file(file_name):
return bottle.static_file(file_name, "/full/path/to/your/static/file/root/")
The relevant Bottle docs are here; or see one of the many posts describing how to serve static file from Bottle.
Is it possible to redirect to a page on 404 and 500 instead of constructing a custom response? I tried-
class NotFoundPageHandler(webapp.RequestHandler):
def get(self):
#if 400
self.redirect('error/notfound.html')
#if 500 how to check
def main():
application = webapp.WSGIApplication(
[
('/', MainPage),
('/index.html', MainPage),
('.*', NotFoundPageHandler)
], debug=True)
But it doesn't work.
You don't want to redirect. What you want is a custom error page.
http://code.google.com/appengine/docs/python/config/appconfig.html#Custom_Error_Responses
error_handlers:
- file: default_error.html
- error_code: over_quota
file: over_quota.html
- error_code: 404 or - error_code: 500 should work too. Read that link carefully, it sounds like you have to be careful those files aren't in a static file directory.