简体   繁体   English

如何从另一个 python 文件中调用 def python

[英]How to call def python from another python file

Hi I have Python script pruebas.py and would like to call from another python script that actually is a Flask (API).嗨,我有 Python 脚本 pruebas.py 并想从另一个 python 脚本调用,该脚本实际上是 Flask (API)。 sound wired but to avoid CORS problem it run on backend side (where works) and I can retrive from the external API.声音有线,但为了避免 CORS 问题,它在后端运行(工作的地方),我可以从外部 API 检索。

This is the code for the file that retrive data from externa API:这是从外部 API 检索数据的文件的代码:

import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase

API_KEY = "xxxxxxxxxxxxxx"
API_SECRET = "xxxxxxxxxxxxxxxxxxxx"
API_PASS = "xxxxxxxxxxxxxxxxxxxxxxxxxx"

# Create custom authentication for Exchange
class CoinbaseExchangeAuth(AuthBase):
    def __init__(self, api_key, secret_key, passphrase):
        self.api_key = api_key
        self.secret_key = secret_key
        self.passphrase = passphrase

    def __call__(self, request):
        timestamp = str(time.time())
        message = timestamp + request.method + request.path_url + (request.body or b'').decode()
        hmac_key = base64.b64decode(self.secret_key)
        signature = hmac.new(hmac_key, message.encode(), hashlib.sha256)
        signature_b64 = base64.b64encode(signature.digest()).decode()

        request.headers.update({
            'CB-ACCESS-SIGN': signature_b64,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-KEY': self.api_key,
            'CB-ACCESS-PASSPHRASE': self.passphrase,
            'Content-Type': 'application/json'
        })
        return request

api_url = 'https://api.pro.coinbase.com/'

auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)

r = requests.get(api_url + 'accounts/', auth=auth)
#print(json.dumps(r.json(), indent=2, sort_keys=True))

The code from my flask:我的 flask 中的代码:

#import sumTwoNumbers
import pruebas
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

#class sumNumbers(Resource):
#    def get(self, first_number, second_number):
#        return {'data': sumTwoNumbers.sumTwo(first_number,second_number)}

class gdd(Resource):
    def get(self):
        return {'data': gdd.requests.get(api_url + 'accounts/', auth=auth)}

api.add_resource(gdd, '/gdd/')

if __name__ == '__main__':
     app.run(debug=True, host= '0.0.0.0')

Thanks for any help and sorry I not a developer.感谢您的帮助,对不起,我不是开发人员。

The objective is to call my flask API that will retrive information from the external API.目标是调用我的 flask API 将从外部 API 检索信息。

I get this error:我收到此错误:

[28/Apr/2020 22:28:50] "GET /gdd/ HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/home/developer/venv/lib/python3.6/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/developer/venv/lib/python3.6/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/developer/venv/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/developer/venv/lib/python3.6/site-packages/flask_restful/__init__.py", line 468, in wrapper
    resp = resource(*args, **kwargs)
  File "/home/developer/venv/lib/python3.6/site-packages/flask/views.py", line 89, in view
    return self.dispatch_request(*args, **kwargs)
  File "/home/developer/venv/lib/python3.6/site-packages/flask_restful/__init__.py", line 583, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/home/developer/venv/Scripts/flask/app.py", line 15, in get
    return {'data': gdd.requests.get(api_url + 'accounts/', auth=auth)}
AttributeError: type object 'gdd' has no attribute 'requests'

It seems like what you want is:看起来你想要的是:

Replace the更换

gdd.requests.get(api_url + 'accounts/', auth=auth)

With:和:

import requests    

requests.get(api_url + 'accounts/', auth=auth)

Documentation文档

Perhaps you may haven't yet referred to the Flask-Restful nor requests documentation, so I'll paste their links here and I encourage you to take a look at it.也许你可能还没有提到 Flask-Restful 也没有请求文档,所以我将它们的链接粘贴在这里,我鼓励你看一看。

The Resource Class : https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Resource资源 Class : https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Resource

Requests : https://requests.readthedocs.io/en/master/请求https://requests.readthedocs.io/en/master/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM