500 error

Hey guys, I could finally overcome some errors, but now I’m getting a new one hehe.

When I run my application, this is everything I get. I already tried to delete this one upload it and deploy again. I also cleared cache.

Does anyone have any ideas on how could I solve this?

Best,

Hi @tiago4maral! :wave:

Can you please send us a link to your code?

Thanks,
Charly

Hey @Charly_Wargnier, sure!

Here:

import requests
import pandas as pd
import streamlit as st
from decouple import config
from apscheduler.schedulers.background import BackgroundScheduler

# Bitquery API key
bitquery_api_key = config("BITQUERY_API_KEY", default="API_KEY")

# Ethereum address you want to query
ethereum_address = "0xc99B3eF8eFD7eE8AC2F67b12862f9704dbD230FA"

# Wrapped Ether (WETH) contract address on Ethereum Mainnet
weth_contract_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"

# Construct the API URL for Bitquery
api_url = 'https://graphql.bitquery.io/'

# GraphQL query to fetch token balances
query = f"""
{{
  ethereum(network: ethereum) {{
    address(address: {{is: "{ethereum_address}"}}) {{
      balances {{
        currency {{
          address
          symbol
          tokenType
          name
        }}
        value
      }}
    }}
  }}
}}
"""

# Set headers with the Bitquery API key
headers = {'X-API-KEY': bitquery_api_key}

# Function to fetch data
def fetch_data():
    try:
        # Send the GraphQL query
        response = requests.post(api_url, json={'query': query}, headers=headers)
        response.raise_for_status()  # Raises a HTTPError if the response status is 4xx, 5xx
    except requests.exceptions.RequestException as e:
        print(f"Error: Cannot fetch data from Bitquery API. {str(e)}")
        return

    data = response.json()
    ethereum_data = data.get('data', {}).get('ethereum', {})

    ethwalletbalance = pd.DataFrame()  # Define the DataFrame outside the if-block

    if ethereum_data:
        addresses_data = ethereum_data.get('address', [])[0]['balances']

        for address_data in addresses_data:
            balances = address_data.get('balances', [])

            for balance in balances:
                value = balance.get('value', 0)
                token_address = balance['currency'].get('address', '')
                token_price_usd = 0  # Initialize token price

                if token_address == weth_contract_address:
                    # Use 1 ETH as the price for WETH
                    token_price_usd = 1.0

                # Fetch token price in USD from CoinGecko using the token's contract address
                coingecko_api_url = "https://api.coingecko.com/api/v3/simple/token_price/ethereum"
                coingecko_params = {
                    'contract_addresses': token_address,
                    'vs_currencies': 'usd'
                }
                try:
                    coingecko_response = requests.get(coingecko_api_url, params=coingecko_params)
                    coingecko_response.raise_for_status()
                except requests.exceptions.RequestException as e:
                    print(f"Error: Cannot fetch data from CoinGecko API. {str(e)}")
                    return

                if coingecko_response.status_code == 429:  # Rate limit error
                    print("Error: CoinGecko rate limit exceeded. Please try again later.")
                    return

                coingecko_data = coingecko_response.json()
                token_price_usd = coingecko_data.get(token_address.lower(), {}).get('usd', 0)

                # Calculate token balance in USD
                token_balance_usd = value * token_price_usd

                # Create a data row for the DataFrame
                data_row = {
                    'ETH_Balance': token_balance_usd
                }
                ethwalletbalance = ethwalletbalance.append(data_row, ignore_index=True)

        # Display the dataframe in Streamlit
        st.dataframe(ethwalletbalance.style.highlight_max(axis=0))

# Schedule the task to run daily at 2 PM Brazil time
scheduler = BackgroundScheduler()
scheduler.add_job(fetch_data, 'cron', day_of_week='mon-sun', hour=6, minute=36, second=0, timezone='America/Sao_Paulo')
scheduler.start()

# This is the Streamlit part of your code
st.title("Ethereum Wallet Balance")

And this is my environment:

Screenshot 2023-09-05 at 08.35.08

I investigated more but couldn’t find any solution.

It’s printing the statement (Eth Balance…), but it’s not getting the data and I get a 500 error in the console.

Could anyone help me with this?

Hi @tiago4maral

Your app is reliant on external APIs (Bitquery and CoinGecko). Have you ensured these APIs are responding correctly and not causing the 500 error?

Also, does your app work in a local environment?

Thanks,
Charly

Have you created the streamlit secrets for the API’s you are using under ‘Advanced Settings’ while deploying the app?

Thank you @Navin_Chandra , I didn’t do that.

There is a tutorial I can follow?

Best,

Yes there is - Secrets management - Streamlit Docs

1 Like

Great, thanks!

I added the Secrets there.

Now, the error is different:



Not sure what is happening.