1
votes

from flask import Flask from flask import render_template, redirect, request from flask_restful import Resource, Api import requests import pickle

app = Flask(name) api = Api(app)

class HelloWorld(Resource): def post(self): r = requests.get('https://samples.openweathermap.org/data/2.5/weather?zip=16802,us&appid=157d320b7d029e653c67902f982784ff')

    json_object_r = r.json()
    temp_k = float(json_object_r['main']['temp'])
    temp_c = temp_k - 273.15
    tempp_c = int(temp_c)

    pickle_in = open("var.pickle", "wb")
    tempp_c = pickle.load(pickle_in)



    # pressure

    p = requests.get('https://samples.openweathermap.org/data/2.5/weather?zip=16802,us&appid=157d320b7d029e653c67902f982784ff')

    json_object_p = p.json()
    press_k = float(json_object_p['main']['pressure'])

    # wind
    # speed
    w = requests.get('https://samples.openweathermap.org/data/2.5/weather?zip=16802,us&appid=157d320b7d029e653c67902f982784ff')

    json_object_w = w.json()
    wind_k = float(json_object_w['wind']['speed'])

    # gust
    g = requests.get('https://samples.openweathermap.org/data/2.5/weather?zip=16802,us&appid=157d320b7d029e653c67902f982784ff')

    json_object_g = g.json()
    gust_g = float(json_object_g['wind']['gust'])


    return {tempp_c}

api.add_resource(HelloWorld, '/')

if name == 'main': app.run(debug=True)

1
try return json.dumps(tempp_c). If it's not json serialisable - consider some binary format - you can even send a pickled object back - if the endpoint is meant for applications.avloss
How do you send a pickled object back?Sonam Rinchen

1 Answers

0
votes

Create a program which sends serialised object first:

import flask
import pickle
object_to_send = {1:2}

@app.route('/endpoint')
def endpoint():
    return pickle.dumps(object_to_send).hex()

app.run(port=8080)

Then you can call it from another python program and read that object:

import pickle
import requests

object_hex = requests.get('http://127.0.0.1:8080/endpoint').text
object_received = pickle.loads(bytearray.fromhex(object_hex))

print(object_received)

This is definitely not a best practice - perhaps you should serialise as json, if at all possible, or use some framework for messaging, which should support different serialisation methods, or a message bus, like Kafka.