0

I'm trying to use a environment variables with hug. However, I can't.

first step how i did:

$ export INTEGER=5

I have this in my main code:

import hug
import os


@hug.get('/')
def foo():
   var = os.environ['INTEGER']
   return {'INT':var}

when i execute

sudo hug -p 80 -f foo.py

and go to localhost/

Error:

Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/lib/python3.6/site-packages/falcon/api.py", line 244, in __call__
    responder(req, resp, **params)
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/lib/python3.6/site-packages/hug/interface.py", line 734, in __call__
    raise exception
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/lib/python3.6/site-packages/hug/interface.py", line 709, in __call__
    self.render_content(self.call_function(input_parameters), request, response, **kwargs)
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/lib/python3.6/site-packages/hug/interface.py", line 649, in call_function
    return self.interface(**parameters)
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/lib/python3.6/site-packages/hug/interface.py", line 100, in __call__
    return __hug_internal_self._function(*args, **kwargs)
  File "repro.py", line 7, in foo
    var = os.environ['INTEGER']
  File "/Users/Andres/.local/share/virtualenvs/botCS-HzHaMvtf/bin/../lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'INTEGER'

what is wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Maverick94
  • 227
  • 4
  • 15

2 Answers2

1

Your problem is that you are running hug as sudo (something you should never do btw.) and adding environment variable as you (a normal user).

I'm guessing that you are running as sudo because you want to run on port 80. Run it rather on port 8080.


So this works:

shell:

export INTEGER=5

python code:

import os

@hug.get('/')
def view():
    print(os.environ['INTEGER'])  # or print(os.environ.get('INTEGER'))

shell:

hug -f app.py -p 8080
mislavcimpersak
  • 2,880
  • 1
  • 27
  • 30
  • if i want to run on port 80, i need to use `sudo`. Anyway, it works your answer on port 8080. Thank you so much. – Maverick94 Feb 04 '18 at 20:56
0

os.environ['INTEGER'] fails because os.environ has no key called "INTEGER".

You can use this code, and provide an optional default as the second arg to get:

os.environ.get("INTEGER", 0)

This will return 0 (or whatever default you supply) if INTEGER is not found.

The reason INTEGER is missing must be related to where you defined your bash variable. It must be "in scope" or accessible to the script based on where you are running the script.

JacobIRR
  • 8,545
  • 8
  • 39
  • 68