Flask Application Not Updating Information on Profile Page or the entire site actually

144 views Asked by At

Description:

I'm working on a Flask web application where agents can update their profile information. The application allows agents to modify their email, phone number, first name, last name, bio, and social media accounts (Twitter, Facebook, Instagram). The updating process involves submitting a form to the server, which then updates the corresponding information in the MySQL database.

Problem:

The issue I'm facing is that when an agent updates their profile information through the form, the changes are not immediately reflected on the profile page or even on the entire site actually. The database is updated successfully, but the profile page or the entire site still displays the old information until I restart the Flask server. This means that other parts of the website that rely on the agent's updated information are also not functioning correctly until the server is restarted.

Code Details:

Here's a summary of the relevant code snippets in my Flask application:

agent_profile Route:

  • The route renders the profile page and handles the POST request for updating the agent's information.
  • The control_database module is used to fetch and update agent data in the database.

control_database Module:

The module contains the agent_profile and update_agent_profile methods for fetching and updating agent information in the database.

Caching:

I added caching to the agent_profile method using Flask-Caching to avoid unnecessary database queries for the same agent's information. But I removed them after I saw the current problem and it seems that the problem still exists.

Code Sample:

# Code of the agent_profile route
@app.route('/profile', methods=["GET", "POST"])
def agent_profile():
    # Retrieve customer list
    customer_list = control_database.customer_list()

    # Check if the user is logged in
    if 'loggedin' not in session:
        # User is not logged in, redirect to the login page
        return redirect(url_for('login'))

    agent_id = session['agent_id']
    agent_data = control_database.agent_profile(agent_id)

    if request.method == 'POST':
        # Check if all required fields are in the form data
        required_fields = ['email', 'phone_number', 'first_name', 'last_name', 'facebook_account', 'instagram_account', 'twitter_account', 'bio']
        if all(field in request.form for field in required_fields):
            # Extract form data
            email = request.form['email']
            phone_number = request.form['phone_number']
            first_name = request.form['first_name']
            last_name = request.form['last_name']
            facebook_account = request.form['facebook_account']
            instagram_account = request.form['instagram_account']
            twitter_account = request.form['twitter_account']
            bio = request.form['bio']

            # Update the agent profile in the database
            social_media = {
                "twitter_account": twitter_account,
                "facebook_account": facebook_account,
                "instagram_account": instagram_account
            }
            control_database.update_agent_profile(agent_id, first_name, last_name, email, phone_number, bio, social_media)

            # Fetch the updated agent data
            new_agent_data = control_database.get_agent_data(agent_id)

            # Inform the user about the successful update
            msg = 'You have successfully updated!'
        else:
            msg = 'Please fill out the full form'

        # Render the template with the updated data and message
        return render_template('profile.html', agent_id=agent_id, agent_data=new_agent_data, customer_list=customer_list, msg=msg)

    # Render the template with the agent data and customer list
    return render_template('profile.html', agent_id=agent_id, agent_data=agent_data, customer_list=customer_list)
# control_database module
class DatabaseControl:
    # Existing methods...
# Method to update the agent's profile in the database
    def update_agent_profile(self, agent_id, first_name, last_name, email, phone_number, bio, social_media):
        # Code for updating the agent's information in the database
                try:
            # Connect to the database
            cursor = connection.cursor()

            # Convert social_media dictionary to JSON string
            social_media_json = json.dumps(social_media)

            # SQL query to update the agent's profile
            update_query = """UPDATE agents SET username=%s, first_name=%s, last_name=%s, email=%s, phone_number=%s, bio=%s, social_media=%s WHERE agent_id=%s"""
            data = (
            f"{first_name} {last_name}", first_name, last_name, email, phone_number, bio, social_media_json, agent_id)

            # Execute the query and commit the changes
            cursor.execute(update_query, data)
            connection.commit()

            # Close the cursor and connection
            cursor.close()
            connection.close()

            return True  # Indicate successful update
        except Exception as e:
            print("Error updating agent profile:", e)
            return False  # Indicate update failure

    
    # Code for fetching the agent's information from the database
    # Retrieve agen data from agents table
    def get_agent_data(self, agent_id):
        try:
            with self.connection.cursor() as cursor:
                cursor.execute("""
                    SELECT * FROM agents
                    WHERE agent_id = %s
                    ORDER BY agent_id DESC
                    LIMIT 1
                """, (agent_id,))
                result = cursor.fetchall()
                if result:
                    results_in_list = result[0]
                    required_data = {
                        "agent_id": results_in_list[0],
                        "agent_username": results_in_list[1],
                        "agent_first_name": results_in_list[2],
                        "agent_last_name": results_in_list[3],
                        "agent_email": results_in_list[4],
                        "agent_phone_number": results_in_list[5],
                        "agent_bio": results_in_list[7],
                        "agent_profile_photo": results_in_list[8],
                        "agent_tasks": results_in_list[9],
                        "agent_notes": results_in_list[10],
                        "agent_social_media": json.loads(results_in_list[12]),
                        "agent_color_scheme": results_in_list[13],
                        "agent_theme_mode": results_in_list[14]
                    }
                    return required_data
                else:
                    return None
        except Exception as e:
            print("Error retrieving agent data:", e)
            return None

Attempts:

I've attempted to use Flask-Caching to cache the agent_profile method and avoid redundant database queries and I removed that when I saw the problem but it seems that the problem still exists. Additionally, I've tried using JavaScript to reload the page after the form submission to display the updated information. However, these attempts have not resolved the issue, and the profile page still shows outdated information until I manually restart the Flask server.

Question:

What could be causing the profile page or even the entire site not to display the updated agent information immediately after submitting the form? Is there something I'm missing or overlooking in my code? Are there any best practices or patterns I should follow to ensure the profile page or the entire site always displays the most recent agent data without requiring a server restart?

Any insights or suggestions would be greatly appreciated. Thank you!

0

There are 0 answers