XeroAPI/xero-python

Facing the error Consult the documentation

bishwadeep opened this issue · 1 comments

Hey guys
I have been trying to resolve this issue for few days now, not able to fix this. I have posted in the community but sadly no replies yet. It was completely working with Oauth v1. However now I have changed it to use v2.

`
default_settings = {
"version": 1,
"formatters": {
"default": {"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"},
"verbose": {
"format": "%(asctime)s | %(levelname)s [%(name)s.%(filename)s:%(lineno)s] %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S%z",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://flask.logging.wsgi_errors_stream",
"formatter": "verbose",
"level": "DEBUG",
}
},
"loggers": {
"requests_oauthlib": {"handlers": ["console"], "level": "DEBUG"},
"xero_python": {"handlers": ["console"], "level": "DEBUG"},
"urllib3": {"handlers": ["console"], "level": "DEBUG"},
},
}
dictConfig(default_settings)

    # configuremain flask application
    app = Flask(__name__,instance_relative_config=True)
    app.config.from_pyfile("config.py", silent=True)
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    # configure persistent session cache
    Session(app)

    # configure flask-oauthlib application
    oauth = OAuth(app)

xero = oauth.remote_app(
name="xero",
version="2",
client_id="A580F8B2D11B40A7BAD3DDC0EAEE31AE",
client_secret="REDACTED",
endpoint_url="https://api.xero.com/",
authorization_url="https://login.xero.com/identity/connect/authorize",
access_token_url="https://identity.xero.com/connect/token",
refresh_token_url="https://identity.xero.com/connect/token",
scope="offline_access openid profile email accounting.transactions "
"accounting.transactions.read accounting.reports.read "
"accounting.journals.read accounting.settings accounting.settings.read "
"accounting.contacts accounting.contacts.read accounting.attachments "
"accounting.attachments.read assets projects "
"files "
"payroll.employees payroll.payruns payroll.payslip payroll.timesheets payroll.settings",
)
# type: OAuth2Application

    xero_tenant_id = "63965a3d-640b-4f2d-9ccc-48d0f38ce09b"
    api_client = ApiClient(
            Configuration(
                    debug=False,
                    oauth2_token=OAuth2Token(
                            client_id="A580F8B2D11B40A7BAD3DDC0EAEE31AE", client_secret="REDACTED"
                    ),
            ),
            pool_threads=1,
    )

    # configure token persistence and exchange point between app session and xero-python
    @xero.tokengetter
    @api_client.oauth2_token_getter
    def obtain_xero_oauth2_token():
            return session.get("token")

    @xero.tokensaver
    @api_client.oauth2_token_saver
    def store_xero_oauth2_token(token):
            session["token"] = token
            session.modified = True

@app.route("/login")
def login():
redirect_url = url_for("oauth_callback", _external=True)
session["state"] = app.config["STATE"]
try:
response = xero.authorize(callback_uri=redirect_url, state=session["state"])
except Exception as e:
print(e)
raise
return response

    @app.route("/callback")
    def oauth_callback():
            if request.args.get("state") != session["state"]:
                    return "Error, state doesn't match, no token for you."
            try:
                    response = xero.authorized_response()
            except Exception as e:
                    print(e)
                    raise
            if response is None or response.get("access_token") is None:
                    return "Access denied: response=%s" % response
            store_xero_oauth2_token(response)
            return redirect(url_for("index", _external=True))


    # call the Xero API
    accounting_api = AccountingApi(api_client)

`

Oauth Version 1 submit invoice working fine
xero.invoices.put(invoice)

Oauth version 2 submit invoice line below
accounting_api.create_invoices(xero_tenant_id, invoice, True)

Getting the following error:
Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.

Hey @bishwadeep, apologies for the delay. If you're still having this issue, could you confirm at which step this error is thrown? Is it when initializing the Xero client, the auth flow, or when calling create_invoices. That's a flask error so I think the issue might be with the sample app not the SDK