Parse result into JSON using Python and Flask - python

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

Related

flask-apispec not populating kwargs with values from GET query (implementation of example code from documentation)

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.

I keep getting this error: "jinja2.exceptions.TemplateNotFound: index.html"

i tried to save index.html file in template folder but still it does work. any help would be highly appreciated. here is my code: am using sypder.
#importing neccessary libs
import numpy as np
from flask import Flask,request,render_template
from flask_cors import CORS
import os
import joblib
import pickle
import flask
import newspaper
from newspaper import Article
import urllib
import nltk
nltk.download('punkt')
#loading flash and assigning the model variable
app= Flask(__name__)
CORS(app)
app=flask.Flask(__name__,template_folder='templates')
#handle
with open('model.pk1','rb') as handle:
model= pickle.load(handle)
#app.route('/')
def main():
return render_template('templates/index.html')
#receiving the input url from the user and using web scrapping to
extract th news content
#app.route('/predict',methods=['GET','POST'])
def predict():
url=request.get_data(as_text=True)[5:]
url=urllib.parse.unquote(url)
article=Article(str(url))
article.download()
article.parse()
article.nlp()
news=article.summary
#passing the news article to the model and returning whether it
is Fake or Real
pred=model.predict([news])
return render_template('index.html', prediction_text='The news
is "{}"'.format(pred[0]))
if __name__=="__main__":
port=int(os.environ.get('PORT',5000))
app.run(port=port,debug=True, use_reloader=False)
I'm not sure how is your project structure, but there could be two possible reasons:
This can be changed:
app= Flask(__name__)
CORS(app)
app=flask.Flask(__name__,template_folder='templates')
into:
app= Flask(__name__, template_folder='templates')
CORS(app)
And since you defend the template folder as templates, return render_template('templates/index.html') should change to return render_template('index.html').
Otherwise you're rendering templates/templates/index.html.
Another reason could be the path.
Since it is relative path, do think if it can be ../templates or ../../templates.

os.getenv() is not pulling a variable I previously declare

I'm new to python and I cannot seem to figure out why I cannot get the os.getenv() function to work. It keeps returning None which is the default value if something is not there. Here is my code:
import os
import datetime
import plaid
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
app = Flask(__name__)
PLAID_CLIENT_ID='entercharhere'
PLAID_ENV='sandbox'
#edit here
os.environ['PLAID_CLIENT_ID']='entercharhere'
os.environ['PLAID_ENV']='sandbox'
print(PLAID_CLIENT_ID)
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV','sandbox')
print(PLAID_CLIENT_ID)
The output I am receiving is entercharhere and None
EDIT
I wound up switching my declaration of variables to send them to the environment using this:
os.environ['PLAID_CLIENT_ID']='entercharhere'
os.environ['PLAID_ENV']='sandbox'
Is this the best way to do it?
Works perfectly:
import os
os.environ['SOMEVAR'] = 'bla'
print(os.getenv('SOMEVAR'))
# in your shell: export SOMEVAR1="blabla"
print(os.getenv('SOMEVAR1'))
Gives:
bla
blabla

Python Google Maps API Stopped working

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,

webpy: How to serve JSON

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

Categories