pythonflaskshopify

Scoping with variables in Flask when calling ShopifyAPI


I have a flask server setup as follows:

from flask import Flask
import shopify

app = Flask(__name__)

# Setup ShopifyAPI
private_app_password = os.getenv("SHOPIFY_API_KEY")
shop_url = os.getenv("shop_url")
api_version = "2024-07"
shopify_session = shopify.Session(shop_url, api_version, private_app_password)
shopify.ShopifyResource.activate_session(shopify_session)


@app.route("/", methods=["POST"])
def index():
    shopify.Orders.find("id"=id)

The code above does not work and returns authentication error. I tried and found out that when I move line 4 + 5 of the setup code to within index(), it works. But I couldn't wrap my head around why that is the case. More specifically, I do not understand why pirvate_app_password, and shop_url is visible within index, while shopify_session is not.

Code that works:

from flask import Flask
import shopify

app = Flask(__name__)

# Setup ShopifyAPI
private_app_password = os.getenv("SHOPIFY_API_KEY")
shop_url = os.getenv("shop_url")
api_version = "2024-07"

@app.route("/", methods=["POST"])
def index():
    shopify_session = shopify.Session(shop_url, api_version, private_app_password)
    shopify.ShopifyResource.activate_session(shopify_session)
    shopify.Orders.find("id"=id)

Does it have anything to do with whether the code is executed before app = Flask(__name__)?

I have moved 2 lines of code into the index function, and it works. But I am unable to find out the reason behind it due to a gap in my understanding of flask, or python?


Solution

  • This issue happens because of lifecycle of Flask. In your initial code you create Shopify session ONLY ONCE, at application start, so session could simply expire by the time a request is made, however Shopify requires active session AT EACH REQUEST.

    Therefore, when you put session creation in router, new session is created for each request.

    Here is link to shopify documentation, that mentions short lifetime of session: https://shopify.dev/docs/apps/build/authentication-authorization/session-tokens#lifetime-of-a-session-token