[英]How to access a library of methods?
I need consume some methods defined in a library. 我需要使用库中定义的一些方法。 In my module, I have 在我的模块中,我有
/mymodule/lib/mod.py
And my views.py
in /mymodule/views.py
和我的views.py
在/mymodule/views.py
In my mod.py
I have declared: 在我的mod.py
我声明了:
class ModClient(object):
"""REST client for Mod API"""
def __init__(self, client_id, secret, environment):
self.client_id = client_id
self.secret = secret
self.environment = environment
def _base_url(self):
base_url = ''
if self.environment == 'sandbox':
base_url = 'https://sandbox.mod.com'
elif self.environment == 'development':
base_url = 'https://development.mod.com'
elif self.environment == 'production':
base_url = 'https://production.mod.com'
return base_url
def _base_params(self):
params = {
'client_id': self.client_id,
'secret': self.secret
}
return params
def _parse_response(self, response):
result = response.json()
if response.status_code != 200:
raise ModClientException(message='HTTP status {}: {}'.format(response.status_code, result),
http_status=response.status_code,
error_type=result.get('error_type', None),
error_code=result.get('error_code', None))
return result
def get_accounts(self, access_token):
url = '{}/accounts/get'.format(self._base_url())
params = self._base_params()
params['access_token'] = access_token
response = requests.post(url, json=params)
return self._parse_response(response)
How I can access to my method get_accounts
from my view.py
assuming that both are in the same module? 假设两者都在同一个模块中,如何从我的view.py
访问方法get_accounts
?
If mymodule
is a package itself and its containing folder is in your environment's PYTHONPATH
, import the class via: 如果mymodule
本身是一个包,并且其包含的文件夹在您环境的PYTHONPATH
,请通过以下方式导入该类:
from lib.mod import ModClient
Then you should be able to instantiate the class in the view and call methods on the instance: 然后,您应该能够在视图中实例化该类并在实例上调用方法:
mc = ModClient()
accounts = mc.get_accounts(token)
A proper IDE (PyCharm, Eclipse, etc.) will do auto-imports for you. 适当的IDE(PyCharm,Eclipse等)将为您自动导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.