I have some python code that uses the Google Maps API that used to work but now for some reason it returns no results. Here is my code
import simplejson
import urllib
import re
GEOCODE_BASE_URL='http://maps.googleapis.com/maps/api/geocode/json'
def geocode(address,sensor,**geo_args):
geo_args.update({
'address': address,
'sensor':sensor
})
url=GEOCODE_BASE_URL+'?'+urllib.urlencode(geo_args)
result=simplejson.load(urllib.urlopen(url))
return simplejson.dumps([s['formatted_address'] for s in result['results']],indent=2)
def main():
city=geocode(address="toronto",sensor="false")
print city
if __name__ == '__main__':
main()
But it shows no results. I swear it used to work, I don't understand what changed.
Thanks,
Related
I am using flask-apispec with webargs to define the types of a simple API. I have produced a minimal example, below, that reproduces the issue, which is that the kwargs object is empty.
Server code:
import flask
from flask_apispec import use_kwargs
from webargs import fields
app = flask.Flask(__name__)
#app.route('/pets', methods=["GET"])
#use_kwargs({'species': fields.Str()})
def list_pets(**kwargs):
assert False, kwargs # NO DATA HERE
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
Simple client script:
import requests
requests.get("http://localhost:5000/pets", params={"species": "cat"})
Why is the kwargs dict empty? I don't see how the above is at all different from the example in the flask-apispec documentation.
I had the same problem and suffered a little with the documentation.
Referencing webargs docs (that is what I understood flask-apispec uses under the hood) I found some examples and was able to implement it.
The location parameter is what was missing.
In your example it would be:
#app.route('/pets', methods=["GET"])
#use_kwargs({'species': fields.Str()}, location="query")
def list_pets(**kwargs):
print(kwargs) # Now "species" should be here if sent through the query
I'm using flask-apispec v0.11.1, which installed webargs v8.1.0 on my system.
Now, I managed to successfully pull basic information from my smart device onto the terminal using pyHS100 on python (v3.6) using the following code
from pyHS100 import SmartPlug
from pprint import pformat as pf
plug = SmartPlug("10.xxx.xxx.xxx")
print("Hardware: %s" % pf(plug.hw_info))
which results in the following:
but I can't parse the data into json format and display it on the local server for my RESTful API purpose if I done it this way:
from flask import Flask, jsonify
from flask_restful import Resource, Api
from pyHS100 import SmartPlug
app = Flask(__name__)
#app.route('/api')
def get():
plug = SmartPlug("10.xxx.xxx.xxx")
sys = plug.hw_info
return jsonify({'data':sys})
if __name__ == '__main__':
app.run(host='0.0.0.0')
app.run(debug=True)
All I need is for the information to be presented into something like this:
What did I do wrong and how do I this fix? Thanks
I believe the best way to solving this is by using json.dumps
I have some code which I would like to be decoded but not having much luck in guessing what the codepage is, if any is being used. Any help would be much appreciated.
i am using python command line in windows 7 pc,if any python guru guide me how to decrypt and see the code thaat would be appreciated.
exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("NTQgYgo1NCA3CjU0IDMKNTQgMWUKNTQgOQo1NCAxOAozZiAgICAgICA9IGIuMTAoKQoxNiAgID0gIjQzOi8vMTIuM2QvNGMvMWQuMjUuZi00ZC4zZSIKYSA9ICIxZC4yNS5mIgoyYSA4KDYpOgoJMzMgMy5jKCczYy4yZSglNTIpJyAlIDYpID09IDEKCjJhIDE1KDM1KToKCTUgPSAzLjQoMWUuNS4xYygnMTM6Ly8yZC8xZicsJzMwJykpCgkyMyA1CgkyMSA9IDcuMTQoKQoJMjEuMzgoIjEwIDI4IiwiMjAgMTAuLiIsJycsICczNiA0MCcpCgkxMT0xZS41LjFjKDUsICdlLjNlJykKCTM5OgoJCTFlLjFhKDExKQoJMWI6CgkJMmMKCQk5LmUoMzUsIDExLCAyMSkKCQkyID0gMy40KDFlLjUuMWMoJzEzOi8vMmQnLCcxZicpKQoJCTIzIDIKCQkyMS4zNCgwLCIiLCAiM2IgNDciKQoJCTE4LjQ4KDExLDIsMjEpCgkJCgkJMy41MygnMjIoKScpOyAKCQkzLjUzKCcyNigpJyk7CgkJMy41MygiNDUuZCgpIik7IAoJCTE5PTcuMzcoKTsgMTkuNTAoIjMyISIsIjJmIDNhIDQ5IDQxIDI5IiwiICAgWzI0IDQ2XTMxIDUxIDRhIDRlIDE3LjNkWy8yNF0iKQoJCSIiIgoJCTM5OgoJCQkxZS4xYSgxMSkKCQkxYjoKCQkJMmMKCQkJIzI3KCkKCQk0Mjo0NCgpCgkJIiIiCgoyYSAyYigpOgoJNGYgNGIgOChhKToKCQkxNSgxNikKCQoKCjJiKCk=")))(lambda a,b:b[int("0x"+a.group(1),16)],"0|1|addonfolder|xbmc|translatePath|path|script_name|xbmcgui|script_chk|downloader|scriptname|xbmcaddon|getCondVisibility|UpdateLocalAddons|download|supermax|Addon|lib|supermaxwizard|special|DialogProgress|INSTALL|website|SuperMaxWizard|extract|dialog|remove|except|join|plugin|os|addons|Installing|dp|UnloadSkin|print|COLOR|video|ReloadSkin|FORCECLOSE|Installer|Installed|def|Main|pass|home|HasAddon|SuperMax|packages|Brought|Success|return|update|url|Please|Dialog|create|try|Wizard|Nearly|System|com|zip|addon|Wait|been|else|http|quit|XBMC|gold|Done|all|has|You|not|sm|MP|By|if|ok|To|s|executebuiltin|import".split("|")))
The code is uglified. You can unobfuscate it yourself by executing the contents of exec(...) in your Python shell.
import re
import base64
print ((lambda p,y.....split("|")))
EDIT: As snakecharmerb says, it is generally not safe to execute unknown code. I analysed the code to find that running the insides of exec will only decrypt, and leaving off the exec itself will just result in a string. This procedure ("execute stuff inside exec") is by no means a generally safe method to decrypt uglified code, and you need to actually analyse what it does. But, at this point, I was asking you to trust my judgement, which, if it is wrong, theoretically could expose you to an attack. In addition, it seems you have problems getting it to run on your Python; so here's what I'm getting from the above:
import xbmcaddon
import xbmcgui
import xbmc
import os
import downloader
import extract
addon = xbmcaddon.Addon()
website = "http://supermaxwizard.com/sm/plugin.video.supermax-MP.zip"
scriptname = "plugin.video.supermax"
def script_chk(script_name):
return xbmc.getCondVisibility('System.HasAddon(%s)' % script_name) == 1
def INSTALL(url):
path = xbmc.translatePath(os.path.join('special://home/addons','packages'))
print path
dp = xbmcgui.DialogProgress()
dp.create("Addon Installer","Installing Addon..",'', 'Please Wait')
lib=os.path.join(path, 'download.zip')
try:
os.remove(lib)
except:
pass
downloader.download(url, lib, dp)
addonfolder = xbmc.translatePath(os.path.join('special://home','addons'))
print addonfolder
dp.update(0,"", "Nearly Done")
extract.all(lib,addonfolder,dp)
xbmc.executebuiltin('UnloadSkin()');
xbmc.executebuiltin('ReloadSkin()');
xbmc.executebuiltin("XBMC.UpdateLocalAddons()");
dialog=xbmcgui.Dialog(); dialog.ok("Success!","SuperMax Wizard has been Installed"," [COLOR gold]Brought To You By SuperMaxWizard.com[/COLOR]")
"""
try:
os.remove(lib)
except:
pass
#FORCECLOSE()
else:quit()
"""
def Main():
if not script_chk(scriptname):
INSTALL(website)
Main()
I am using guv and feedparser to parse multiple feeds simultaneously. The following is my code:
guv.monkey_patch(time=True, socket=True)
def parse_feed(_feed):
return feedparser.parse(_feed)
def main():
urls = ["http://feeds.bbci.co.uk/news/rss.xml"]
pool = guv.GreenPool()
results = pool.starmap(parse_feed, zip(urls))
for resp in results:
print(str(resp))
However, I get the following output:
{'bozo_exception': TypeError('a float is required',), 'bozo': 1, 'feed': {}, 'entries': []}
I have the similar problem using Eventlet, but not with native Python 3 threading library.
I'm not able to install the guv module locally, so I can't test your code verbatim, but if I use eventlet.greenpool.GreenPool instead everything works fine:
import feedparser
import eventlet.greenpool
def parse_feed(_feed):
print 'PARSE:', _feed
return feedparser.parse(_feed)
def main():
urls = ["http://feeds.bbci.co.uk/news/rss.xml"]
pool = eventlet.greenpool.GreenPool()
results = pool.starmap(parse_feed, zip(urls))
for resp in results:
print resp
main()
I also see correct behavior with itertools.starmap(). Is it possible you're seeing some sort of transient error?
Is it possible to use webpy to serve JSON?
I built my website and I need to serve some information in JSON to interact with the Javascript on some pages.
I try to look for answers in the documentation, but I'm not able to find anything.
Thanks,
Giovanni
I wouldn't think you'd have to do any thing overly "special" for web.py to serve JSON.
import web
import json
class index:
def GET(self):
pyDict = {'one':1,'two':2}
web.header('Content-Type', 'application/json')
return json.dumps(pyDict)
It is certainly possible to serve JSON from webpy, But if you and choosing a framework, I would look at starlight and my fork twilight (for documentation).
It has a JSON wrapper for fixing the http headers for your json response.
it uses either the json or simplejson libraries for json handling the conversions to and from other objects.
I am using it right now and it is great.
https://bitbucket.org/marchon/twilight
in it you will find an example called ShowMeTheJson.py
that uses simple json
from starlight import *
from werkzeug.routing import Map
from werkzeug.routing import RuleFactory
import simplejson
class ShowMeTheResponses(App):
####################################################################
#
# Sample URLS to Test Responses
#
# http://localhost:8080/ root
#
# http://localhost:8080/json return JSON Mime Type Doc
#
###################################################################
#default
def hello(self):
return 'Hello, world!'
#dispatch('/')
def index(self):
return 'Hello Root!'
#dispatch('/html')
def indexhtml(self):
return HTML('Hello HTML')
#dispatch('/json')
def indexjson(self):
directions = {'N' : 'North', 'S' : 'South', 'E':'East', 'W' : 'West'}
return JSON(simplejson.dumps(directions))
if __name__ == '__main__':
from werkzeug import run_simple
run_simple('localhost', 8080, ShowMeTheResponses())