I'm getting:
Error 413 (Request Entity Too Large)
Using the new Google Cloud Translation API, via Python client. I need to cut my text limit, but not able to find the limit. My request contained 15185 characters.
Looks like my error is not related to Quota limits:
https://cloud.google.com/translate/limits
google.cloud.exceptions.GoogleCloudError: 413 <!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
<title>Error 413 (Request Entity Too Large)!!1</title>
<style>
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}#media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}#media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}#media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
</style>
<a href=//www.google.com/><span id=logo aria-label=Google></span></a>
<p><b>413.</b> <ins>That’s an error.</ins>
<p>Your client issued a request that was too large.
<script>
(function() { var c=function(a,d,b){a=a+"=deleted"+("; path="+d);null!=b&&(a+="; domain="+b);document.cookie=a+"; expires=Thu, 01 Jan 1970 00:00:00 GMT"};var g=function(a){var d=e,b=location.hostname;c(d,a,null);c(d,a,b);for(var f=0;;){f=b.indexOf(".",f+1);if(0>f)break;c(d,a,b.substring(f+1))}};var h;if(4E3<unescape(encodeURI(document.cookie)).length){for(var k=document.cookie.split(";"),l=[],m=0;m<k.length;m++){var n=k[m].match(/^\s*([^=]+)/);n&&l.push(n[1])}for(var p=0;p<l.length;p++){var e=l[p];g("/");for(var q=location.pathname,r=0;;){r=q.indexOf("/",r+1);if(0>r)break;var t=q.substring(0,r);g(t);g(t+"/")}"/"!=q.charAt(q.length-1)&&(g(q),g(q+"/"))}h=!0}else h=!1;
h&&setTimeout(function(){if(history.replaceState){var a=location.href;history.replaceState(null,"","/");location.replace(a)}},1E3); })();
Same situation here although I found the following in the docs:
https://cloud.google.com/translate/quotas
https://cloud.google.com/translate/faq
In the second link there is a specific question about chars per request and it says it shouldn't be more than 5000
Related
I am making a info screen for a few 3D printers, I have a rest API where I get the data from. The data should be updated continuously and it will be name and time. I however want to just start getting the current name displaying on the HTML site.
I have a working Python program that loops and updating the current name and that output needs to go to a specific field, in this case (HTML file field INPUT NAME 1) I will have multiple printers so needs to be easy to direct the data to the HTML tags... Have been trying flask but I do not know if that is the best for this?
python program:
import sched, time
from time import time, sleep
import flask
from flask import Flask, redirect, url_for, render_template, request, flash
import requests
app=Flask(__name__,template_folder='templates')
#printer-S3-nr1
response_ums3_1 = requests.get("http://192.168.50.203/api/v1/print_job/name")
response_ums5_1 = requests.get("http://192.168.50.201/api/v1/print_job/name")
#app.route("/")
def profile():
while (True):
sleep(10 - time()%10)
#ULTIMAKER S3 NR 1
if response_ums3_1.status_code == 404:
return render_template("server.html", s3name1 = "No Prints Running")
if response_ums3_1.status_code == 200:
return render_template("server.html", s3name1 = response_ums3_1.text.strip('"'))
#ULTIMAKER S3 NR 1
#ULTIMAKER S5 NR 1
if response_ums5_1.status_code == 404:
return render_template("server.html", s5name1 = "No Prints Running")
if response_ums5_1.status_code == 200:
return render_template("server.html", s5name1 = response_ums5_1.text.strip('"'))
#ULTIMAKER S5 NR 1
if __name__ == "__main__":
app.run(debug=True)
```
<!DOCTYPE html>
<html>
<head>
<style>
#customers {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#customers td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even) {
background-color: #f2f2f2;
}
#customers tr:hover {
background-color: #ddd;
}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #1b77f7;
color: white;
}
</style>
</head>
<H1 align="center"> Printer Status </H1>
<body>
<table id="customers">
<tr>
<th>Skrivare</th>
<th>Färdig</th>
<th>Namn</th>
<th>Video</th>
</tr>
<tr>
<td>Ultimaker-S5-nr1</td>
<td>INPUT TIME</td>
<td>{{s5name1}}</td>
<td><img src="http://192.168.50.201:8080/?action=stream" alt="Ultimaker-S5-nr1" style="width:202.5px;height:151.85px;" </td>
</tr>
<tr>
<td>Ultimaker S3 nr1</td>
<td>INPUT TIME</td>
<td>{{s3name1}}</td>
<td><img src="http://192.168.50.203:8080/?action=stream" alt="Ultimaker S3 nr1" style="width:202.5px;height:151.85px;" </td>
</tr>
<tr>
</table>
</body>
</html>
```
In Flask, if you want to send data back from server to the front end, then you have to use the return command. Right now, all you're doing is sending output (your print command) to your console. When you return values from your server to the front end, you'll have to use Jinja Template to display the values e.g.
#server code
if response.status_code == 202:
return render_template("index.htm", INPUT_NAME_1 = response.text)
#html page e.g index.htm
....
<td>{{INPUT_NAME_1}}</td>
...
So from the above code (#server code), you're sending a variable called INPUT_NAME_1 back to an html page called index.htm and on that page you get the value of the variable by using the Jinja syntax of double curly brackets i.e. {{}}
Flask is a web framework. It allows you to build web-based applications which use Python. Another framework is Django. If your target is a web application, then you can use any of them.
Note: Right now, your code doesn't include anything to make it web-based. You haven't even imported the Flask libraries to your python code and that brings me to my next point.
Your question shows you're still missing some basics and continuing down this path will lead to more frustration for you. I would advise that you first understand the basics of Flask e.g. read materials that introduce you to Flask. A quick Googling returned the following - https://pymbook.readthedocs.io/en/latest/flask.html,
https://flask.palletsprojects.com/en/2.0.x/
Once you get the basics of Flask, you should then figure out if you want your web application to reside on your local machine or you want to host it on the web. For web hosting, there are cheap (or free) hosts like python anywhere, heroku, Google App Engine. If you decide to go the route of Google App Engine, check out our website where we have a GUI for it
Here's what I'm doing.
I'm sending a get request to a reddit oembed endpoint. I want to parse the returned json and grab the raw html to embed a reddit post onto my django page. The error I receive when I try to do this is
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
Here's an example of that code in action. (It's inside a function)
endpoint = requests.get("https://www.reddit.com/oembed?url=https://www.reddit.com/r/nba/comments/n6l2zu/the_crew_lock_in_their_predictions_and_ernie_has/")
return endpoint.json()['html']
Here is the html it should return. I'm thinking maybe I have to reformat it? Could someone help me out here? Thanks!
'\n <blockquote class="reddit-card" >\n The crew lock in their predictions and Ernie has the Jazz going to the Finals from\n nba\n </blockquote>\n <script async src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>\n'
EDIT:
Here is the result of printing endpoint.json()
{
"provider_url":"https://www.reddit.com/",
"version":"1.0",
"title":"The crew lock in their predictions and Ernie has the Jazz going to the Finals",
"provider_name":"reddit",
"type":"rich",
"html":"\n <blockquote class=\"reddit-card\" >\n The crew lock in their predictions and Ernie has the Jazz going to the Finals from\n nba\n </blockquote>\n <script async src=\"https://embed.redditmedia.com/widgets/platform.js\" charset=\"UTF-8\"></script>\n",
"author_name":"tanookiben"
}
import requests
import json
def get_response():
endpoint = requests.get("https://www.reddit.com/oembed?url=https://www.reddit.com/r/nba/comments/n6l2zu/the_crew_lock_in_their_predictions_and_ernie_has/")
if endpoint.status_code == 200:
return json.loads(endpoint.text)
return {}
print(get_response())
It seems like reddit responses error message as below when you make requests. So it is better to check response status code first.
<!doctype html>
<html>
<head>
<title>Too Many Requests</title>
<style>
body {
font: small verdana, arial, helvetica, sans-serif;
width: 600px;
margin: 0 auto;
}
h1 {
height: 40px;
background: transparent url(//www.redditstatic.com/reddit.com.header.png) no-repeat scroll top right;
}
</style>
</head>
<body>
<h1>whoa there, pardner!</h1>
<p>we're sorry, but you appear to be a bot and we've seen too many requests
from you lately. we enforce a hard speed limit on requests that appear to come
from bots to prevent abuse.</p>
<p>if you are not a bot but are spoofing one via your browser's user agent
string: please change your user agent string to avoid seeing this message
again.</p>
<p>please wait 6 second(s) and try again.</p>
<p>as a reminder to developers, we recommend that clients make no
more than <a href="http://github.com/reddit/reddit/wiki/API">one
request every two seconds</a> to avoid seeing this message.</p>
</body>
</html>
I wasn't sending a proper header. Kept getting a 429 error back, and because there was no json returned, I was receiving the json decoder error.
I'm writing a basic socket programming code in python which takes any kind of URL and returns the content of the body in bytes. I need to only use socket library and nothing else. When I pass different URLs, I get full response of the body for some URLs and only a partial response for some URLs. I'm not sure why it is so.
This is my code:
import socket
def retrieve_url(url):
url1 = url.split("http://", 1)
empty = url1[1].find("/")
if empty > 0:
url2 = url1[1].split("/", 1)
else:
url2 = url1[1].split("/", 1)
url2.append('')
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
soc.connect((url2[0], 80))
soc.sendall(b"GET /" + bytes(url2[1], 'utf8') + b" HTTP/1.1\r\nHost: " + bytes(url2[0],'utf8') + b"\r\nConnection: close\r\n\r\n")
spl = soc.recv(8192)
soc.close()
a = spl.split(b"\r\n\r\n", 1)
b = spl.split(None, 2)
if b[1] == b'200':
return a[1]
else:
return None
except:
return None
if __name__ == "__main__":
print(retrieve_url("http://bombus.myspecies.info/node/24"))
This is the output I'm getting:
b'007a84\r\n<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">\n<html lang="en" dir="ltr" version="HTML+RDFa 1.1"\n xmlns:content="http://purl.org/rss/1.0/modules/content/"\n xmlns:dc="http://purl.org/dc/terms/"\n xmlns:foaf="http://xmlns.com/foaf/0.1/"\n xmlns:og="http://ogp.me/ns#"\n xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"\n xmlns:sioc="http://rdfs.org/sioc/ns#"\n xmlns:sioct="http://rdfs.org/sioc/types#"\n xmlns:skos="http://www.w3.org/2004/02/skos/core#"\n xmlns:xsd="http://www.w3.org/2001/XMLSchema#">\n<head profile="http://www.w3.org/1999/xhtml/vocab">\n <!--[if IE]><![endif]-->\n<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />\n<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<meta name="Generator" content="Drupal 7 (http://drupal.org)" />\n<link rel="canonical" href="/node/24" />\n<link rel="shortlink" href="/node/24" />\n<link rel="shortcut icon" href="http://bombus.myspecies.info/sites/all/themes/scratchpads/favicon.ico" type="image/vnd.microsoft.icon" />\n<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />\n <title>Bumblebee links | Genus Bombus</title>\n <link type="text/css" rel="stylesheet" href="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_css/css__-thr5kmN-aeH-BTlyCidKsE4D9T2geiRzcvwxBTJ3sU__VQtLPGzb9rjfNLJ2SaVDJUKhxtssNArRk3nO7wMUGoA__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.css" media="all" />\n\n<!--[if (lt IE 9)]>\n<link type="text/css" rel="stylesheet" href="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_css/css__GuBcvhFB_-fswxhbycYya2JRgqrqDq5y-pWYcuQbqp4__5h6_elrgEAXONSci50a6ewD4zUldIVoOgFFSjk7rVzg__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.css" media="all" />\n<![endif]-->\n<link type="text/css" rel="stylesheet" href="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_css/css__wxRBHPf0PIq6kCJXm57TkZCESl8zp_O0VduSG6wH0S0__ov4XZtBPHqH1F5cpK65jxEp1K5zF3dLEO4ihA2xTbE8__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.css" media="all" />\n\n<!--[if (lt IE 9)&(!IEMobile)]>\n<link type="text/css" rel="stylesheet" href="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_css/css__ISa-1zfLkp-52D_pPloP6gBpDvJwKu9Kitwbfnm33JY__PDj463LZhTo68R-x__a4AOf-EyYxSMW6sZpiNjtiKlQ__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.css" media="all" />\n<![endif]-->\n\n<!--[if gte IE 9]><!-->\n<link type="text/css" rel="stylesheet" href="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_css/css__Sisgbo-UreLp3cHBWfv37bIck8X5olI1W5xaYzDaATc__9XoSDv750KzHbfRkMww8VsZREmLh-SRR3SnhCYOEF2Q__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.css" media="all" />\n<!--<![endif]-->\n <script type="text/javascript" src="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_js/js__jQBI8pfG-VfYV1aN0gSeRXUYps9-4-M-XVb2H2ZbWuw__SyNVdbb0UiBMvI1oo0AzTY4CH83E7BmTR7ZP1Wwz_VE__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.js"></script>\n<script type="text/javascript" src="//bombus.myspecies.info/sites/all/libraries/mediaelement/build/mediaelement-and-player.min.js?v=2.1.6"></script>\n<script type="text/javascript" src="//bombus.myspecies.info/sites/bombus.myspecies.info/files/advagg_js/js__O2-Mfrpb6mHF0S5LAfIan_d38-kqXvv66sN_ZsHG9Qo__caMiUBuMxDF7rNYJXFf8geEVfuxGw22B96ouV1h3-1Q__CirpVkWrddCrpKWbZfWXvbwVN8pmqviBo8YZAKaYUQg.js"></script>\n<script type="text/javascript">\n<!--//--><![CDATA[//><!--\njQuery.extend(Drupal.settings,{"basePath":"\\/","pathPrefix":"","ajaxPageState":{"theme":"scratchpads","theme_token":"u7Gd7GPT7EPAVsIznB6HVhd9aHAwVUfjG4LrulLh3ak","jquery_version":"1.8","css":{"modules\\/system\\/system.base.css":1,"modules\\/system\\/system.menus.css":1,"modules\\/system\\/system.messages.css":1,"modules\\/system\\/system.theme.css":1,"sites\\/all\\/libraries\\/mediaelement\\/build\\/mediaelementplayer.min.css":1,"misc\\/ui\\/jquery.ui.core.css":1,"misc\\/ui\\/jquery.ui.theme.css":1,"modules\\/overlay\\/overlay-parent.css":1,"sites\\/all\\/modules\\/contrib\\/comment_notify\\/comment_notify.css":1,"modules\\/aggregator\\/aggregator.css":1,"modules\\/comment\\/comment.css":1,"sites\\/all\\/modules\\/contrib\\/date\\/date_api\\/date.css":1,"sites\\/all\\/modules\\/custom\\/entityfilter\\/ckeditor\\/entityfilter.css":1,"sites\\/all\\/modules\\/custom\\/field_quick_delete\\/theme\\/field.css":1,"modules\\/node\\/node.css":1,"sites\\/all\\/modules\\/custom\\/remote_issue_tab\\/css\\/remote_issue_tab.css":1,"sites\\/all\\/modules\\/custom\\/scratchpads\\/scratchpads_biography\\/css\\/scratchpads_biography.css":1,"sites\\/all\\/modules\\/custom\\/scratchpads\\/scratchpads_show_taxa_revisions\\/css\\/scratchpads_show_taxa_revisions.css":1,"modules\\/search\\/search.css":1,"sites\\/all\\/modules\\/custom\\/spm\\/css\\/spm.css":1,"sites\\/all\\/modules\\/custom\\/twitter_filter\\/css\\/twitter_filter.css":1,"sites\\/all\\/modules\\/custom\\/twitterscript\\/css\\/twitterscript.css":1,"modules\\/user\\/user.css":1,"sites\\/all\\/modules\\/contrib\\/views\\/css\\/views.css":1,"sites\\/all\\/modules\\/contrib\\/ckeditor\\/ckeditor.css":1,"sites\\/all\\/modules\\/contrib\\/colorbox\\/styles\\/default\\/colorbox_default_style.css":1,"sites\\/all\\/modules\\/contrib\\/ctools\\/css\\/ctools.css":1,"sites\\/all\\/modules\\/contrib\\/ctools\\/css\\/modal.css":1,"sites\\/all\\/modules\\/contrib\\/modal_forms\\/css\\/modal_forms_popup.css":1,"sites\\/all\\/modules\\/contrib\\/biblio\\/biblio.css":1,"modules\\/openid\\/openid.css":1,"public:\\/\\/spamicide\\/feed_me.css":1,"sites\\/all\\/modules\\/custom\\/scratchpads\\/scratchpads_search_block\\/css\\/scratchpads_search_block.css":1,"sites\\/all\\/modules\\/custom\\/creative_commons\\/css\\/creative_commons.css":1,"sites\\/all\\/themes\\/scratchpads\\/css\\/ie8.css":1,"public:\\/\\/css\\/css_tcVOMdlRmJTsBkm7ZJABjZ3Oct1H-tB7QsRkmUkgNco.css":1,"sites\\/all\\/themes\\/scratchpads\\/css\\/tabs.css":1,"sites\\/all\\/themes\\/scratchpads\\/css\\/sites.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/alpha-reset.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/alpha-mobile.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/alpha-alpha.css":1,"sites\\/all\\/themes\\/omega\\/omega\\/css\\/formalize.css":1,"sites\\/all\\/themes\\/omega\\/omega\\/css\\/omega-text.css":1,"sites\\/all\\/themes\\/omega\\/omega\\/css\\/omega-branding.css":1,"sites\\/all\\/themes\\/omega\\/omega\\/css\\/omega-menu.css":1,"sites\\/all\\/themes\\/omega\\/omega\\/css\\/omega-forms.css":1,"sites\\/all\\/themes\\/scratchpads\\/css\\/global.css":1,"ie::normal::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default.css":1,"ie::normal::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default-normal.css":1,"ie::normal::sites\\/all\\/themes\\/omega\\/alpha\\/css\\/grid\\/alpha_default\\/normal\\/alpha-default-normal-12.css":1,"narrow::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default.css":1,"narrow::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default-narrow.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/grid\\/alpha_default\\/narrow\\/alpha-default-narrow-12.css":1,"normal::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default.css":1,"normal::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default-normal.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/grid\\/alpha_default\\/normal\\/alpha-default-normal-12.css":1,"wide::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default.css":1,"wide::sites\\/all\\/themes\\/scratchpads\\/css\\/scratchpads-alpha-default-wide.css":1,"sites\\/all\\/themes\\/omega\\/alpha\\/css\\/grid\\/alpha_default\\/wide\\/alpha-default-wide-12.css":1},"js":{"modules\\/statistics\\/statistics.js":1,"sites\\/all\\/modules\\/contrib\\/jquer'
I only get partial response for this, but what I need is the full response.
Any help is appreciated. Thanks in advance.
soc.sendall(b"GET /" + bytes(url2[1], 'utf8') + b" HTTP/1.1\r\nHost: " + bytes(url2[0],'utf8') + b"\r\nConnection: close\r\n\r\n")
spl = soc.recv(8192)
soc.close()
You assume that all data will be retrieved with a single recv. This assumption is wrong. Given that you use an explicit Connection: close you can rely on the server closing the connection after the response is done, i.e. you should call recv as long as it returns more data and concatenate all these date for the full response.
You also assume that the answer is contained in plain in the response body. While this might be true in your specific case your use of HTTP/1.1 makes it possible for the server to send a chunked response too - which you need to handle differently. In order to avoid this better use HTTP/1.0 only (which also has an implicit Connection: close).
I am very new to leaflet, and I'm trying to workout how to return the lat and lng from a onMapClick event in leaflet to the flask server app, to allow me to use the coordinates t perform a spatial search on my database. The event currently only shows the lat long in a pop-up on the web app.
I've had a search around, but I guess my knowledge is so basic I don't know what functions I'm searching for.
My web map
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" /> <!-- Leaflet CSS file (style sheets)>-->
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script> <!--leaflet java script file>-->
</head>
<body>
<div id="map1" style="width: 800px; height: 600px;"></div>
<script>
var mymap = L.map('map1').setView([51.5, -0.09], 10);
<!--add map to display>-->
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: '*****************'
}).addTo(mymap);
<!--add popups as a layer>-->
var popup = L.popup();
<!--logs the action and gives lat long of where click occured >-->
function onMapClick(e) {
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
</script>
</body>
</html>
and the server app
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/demo')
def webMap():
return render_template('demo.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8090)
EDIT
I have attempted using an ajax call but getting a 405 error
$.ajax('demo/data/', {
type: 'GET',
data: {
lat: e.latlng.lat,
lng: e.latlng.lng
}
});
};
Flask app
#app.route('/demo/data/')
def demoData():
return request.form['lng'], request.form['lat']
A 405 error is a method not allowed error.
You should use a POST request sending information when using the REST-api, as discussed here.
You're going to want to change your app.route to,
#app.route('/demo/data/' methods=["POST"])
To allow a post method
I am trying to write a web service that performs some data processing. The requests contain a data vector as a binary file, and meta-data and processing parameters as form data. An example using python with requests:
import numpy as np
import requests
url = 'http://localhost:8080/pp'
payload = {'param_a': 4, 'param_b': -2.1}
file = {'binary_data': ('file_name.bin', bytes(np.random.randn(1000))}
r = requests.post(url, data=payload, files=file)
Now on the service side, I have:
import bottle
import numpy as np
#bottle.post('/pp')
def pp():
file_path = '/home/generic_user/howhaveyou.bin'
return_file_path = '/home/generic_user/finethanks.bin'
bin_file = bottle.request.files.get('binary_data')
bin_file.save(file_path, overwrite=True)
param_a = float(bottle.request.forms.get('param_a')
param_b = float(bottle.request.forms.get('param_b')
data_vector = np.fromfile(file_path)
processed_data_vector = (data_vector-param_a)*param_b
processed_data_mean = np.mean(processed_data_vector)
processed_data_samples = len(processed_data_vector)
return_metrics = {'mean': processed_data_mean,
'n_of_samples': processed_data_samples}
with open(return_file_path, 'wb') as return_file:
return_file.write(bytes(processed_data_vector))
return return_metrics, bottle.static_file(return_file_path, '/')
which doesn't quite work. Either of the returns work on their own, but together I get the following response:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error: 500 Internal Server Error</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error: 500 Internal Server Error</h1>
<p>Sorry, the requested URL <tt>'http://localhost:8080/pp'</tt>
caused an error:</p>
<pre>Unsupported response type: <class 'dict'></pre>
</body>
</html>
I have a complete lack of experience with Web Services, so I don't even know if I'm on the right track at all. The point is I wish to return some binary data, along with a few (preferably named) metrics of said data. Is it possible to do this using bottle only? Is there a best practice (with respect to web services, python or both) that I should follow when it comes to this kind of thing?
Note that the client will not be written in python, that is just my test case.
Thanks for any guidance!
The problem with the server-side code is that you cannot return a dictionary (return_metrics) and the contents of a file (return_file_path) with the same response. A solution is to encode the file contents in a string and include it in the returned dict (return_metrics). Then, the client will need to decode the content string to access the data.