-1

First of all, I am very new at programming. I am trying to save a variable from bash shell

  >curl http://169.254.169.254/latest/meta-data/

this line would return data such as local-ipv4. And I am trying to use phython and flask to save those variables. I wrote

from flask import Flask, request
app  = Flask(__name__)
@app.route('/')
def testRequest():
  url1 = "http://169.254.169.254/latest/meta-data/"
  name1 = request.get(url1)
  nameText = name1.text
  return nameText

testOutput = testRequest()
print testOutput

But this gives me runtime error : working outside of the request context. can someone guide me to where to look for possible solution?

programing_is_hard
  • 442
  • 1
  • 6
  • 16
  • See: https://stackoverflow.com/q/4760215/4110233 – TheChetan Sep 05 '17 at 04:10
  • I'm a little confused; are you trying to save data from *incoming* requests? Or are you trying to query url1 and return data from that? My understanding is that Flask's `request` is for the former, whereas you'd probably want to use the `requests` module for the latter. Looking at your code, it seems like `requests` is what you want, rather than Flask's `request` – evamvid Sep 05 '17 at 04:16

2 Answers2

2

To things to comment here:

  1. First, it seems that you'll be just fine by using requests, a highly recommended library for HTTP requests. With it you could do:

    import requests
    url = "http://169.254.169.254/latest/meta-data/"
    resp = requests.get(url)
    print resp.text
    
  2. Regards to the error you're getting runtime error : working outside of the request context, is because by testOutput = testRequest() you're calling a method that's part of the Flask app app. Another thing related to the error is that you never ran the Flask app. To do this, include this at the end of your code.

     if __name__ == '__main__':
        app.run()
    

    But again, Flask is rather a web framework that it's useful to create web sites, APIs, web apps, etc. It's very useful, but I don't think you may need it for what you're trying to achieve.

Further info about requests and Flask:

joegalaxian
  • 350
  • 1
  • 7
  • Thank you so much! first method worked. The reason why I wanted to implement flask is that because I want to make the web apps by using those data. I guess I will implement flask later on. I am not very familiar with either flask or python... – programing_is_hard Sep 05 '17 at 04:22
1

Since you only need to make an HTTP GET request and print the response, you don't need Flask. You can use the urllib standard library to send the GET request (https://docs.python.org/3/library/urllib.request.html):

import urllib.request

def testRequest():
  url1 = "http://169.254.169.254/latest/meta-data/"
  response = urllib.request.urlopen(url1)
  nameText = response.read().decode('utf-8')
  return nameText

testOutput = testRequest()
print testOutput
bazram
  • 11
  • 2