Steps for importing the mongo variable from the app that is bound to the application

I have two files, app.py and views.py

app.py

from flask import Flask
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://local:27017/local"
mongo = PyMongo(app)
from views import profileview
profileview.register(app, route_prefix='/profile/')

if __name__== "__main__":
    app.run(debug=True)

views.py

from flask_classy import FlaskView , route
# I am experiencing difficulty importing the app in views
from app import mongo

class profileview(FlaskView):
    route_base = '/'
    
    @route("/user/", methods=["GET"])
    def index(self):
        pass

When I run the server, it shows an error that it cannot import from views import profileview. How can I address this circular import issue?

Answer №1

Here's a handy tip to prevent circular imports:

database.py

from sqlalchemy import create_engine
engine = create_engine('sqlite:///mydatabase.db')

main.py

if __name__ == '__main__':
    from database import engine

    conn = engine.connect()

models.py

from database import engine

You can also consider using the factory design pattern and implement a create_app function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Python's If Statements and Dictionary Functionality in an Address Book Application

For practice, I am developing a small address book program. Can you help me identify any issues in my code when attempting to add a new entry? Additionally, how can I modify it so that after each action, it goes back to the selection menu (1-4) instead of ...

What is the best way to transform api.Response into a data frame or json format using Python?

Looking at the data I have, my goal is to transform it into a data frame. t = cmc.globalmetrics_quotes_latest() (Cmc refers to the coinmarketcap api) type(t)= coinmarketcapapi.response """ RESPONSE: 820ms OK: {'active_cryptocurrencies ...

How to eliminate excess whitespace surrounding patches in Matplotlib

Looking at the image provided (1), I'm struggling to find a way to eliminate the excessive white space surrounding the hexagonal grid. Despite attempting various methods such as tight_layout, the issue persists. https://i.stack.imgur.com/iFeQq.png T ...

Python Improved approach for generating permutations

I am trying to generate all possible combinations of the letters 'r' and 'u' based on their counts in a given string. Below is an example of a code that accomplishes this task: import itertools RIGHT = 'r' UP = 'u' d ...

What is the process for making an API call in Python with Google App Engine (GAE)?

I've developed a basic web form using Google App Engine with a reCAPTCHA component included. The component is visible on the webpage, but I'm struggling to understand how to execute the API call in my code. def post(self): challenge = self. ...

Arrange a pandas dataframe by the values in a column that contains a combination of single integers and lists with two integers

In my dataset, I have a dataframe called temp_df. line sheet comments 1 apple this is a fruit 2 orange this is fruit [1,3] onion this is a vegetable The goal is to sort the temp_df based on both the sheet and line columns. However, since the l ...

Discovering the xpath with a certain condition based on text length using Python Selenium

In my quest to extract the specific content I need from countless pages, I have devised a reliable rule that works 99% of the time: //a[@class='popular class' and not (contains(text(),'text1')) and not (contains(text(),'text2&apos ...

Invalid operator detected in TypeT5

File "/work/09235/kunjal/ls6/TypeT5/train_model.py", line 112, in <module> wrapper = train_spot_model( File "/work/09235/kunjal/ls6/TypeT5/typet5/train.py", line 180, in train_spot_model trainer.fit( File "/home1/ ...

The repeated issue persists both when upgrading `pip` and when attempting to install a library

While attempting to install python libraries using pip, I first used the command: pip install matplotlib This was the output Following that, I tried: python -m pip install --upgrade pip' I also came across this code on a website ...

Getting the stack with Python selenium webdriver

I tried running this code snippet to test Selenium, but encountered an issue where the Firefox window did not open and no error messages were displayed. The print statement was also not executed. from selenium import webdriver driver = webdriver.Firefox ...

making adjacent violin plots in seaborn

I've been experimenting with creating side-by-side violin plots using Matplotlib and Seaborn, but I'm facing challenges in getting them to display correctly. Instead of being superimposed, I want to compare the average Phast scores for different ...

HubSpot3 customer encountering an issue with the dreaded "excessive retry attempts" error message

I've encountered an issue while trying to retrieve contact details from HubSpot using the recipient's email address. I am utilizing the Python3 client "hubspot3" (https://github.com/jpetrucciani/hubspot3). Below is the code snippet I have implem ...

Retrieve two elements from every item in the PythonList class

Currently, I am using Python 3.8.0 and working on a project. In one part of my code, I have created a list with 4 random items, and now I need to extract the name and HP (Hit Points) from each item in that list. I attempted to use the repr function, but en ...

difficulty connecting scrapy data to a database

Currently, I am attempting to insert scraped items using Scrapy into a MySQL database. If the database does not already exist, I want to create a new one. I have been following an online tutorial as I am unfamiliar with this process; however, I keep encoun ...

Errore in Python con Selenium: TypeError - Oggetto di tipo 'str' non è richiamabile durante la ricerca di un

I encountered the error message: "TypeError: 'str' object is not callable" while running this code: iframe=driver.find_element(By.XPATH("//iframe[contains(@src,'https://pianomarvel.com/uploads/editSlicings/85810')]")); What could be ca ...

Converting for loop to extract values from a data frame using various lists

In the scenario where I have two lists, list1 and list2, along with a single data frame called df1, I am applying filters to append certain from_account values to an empty list p. Some sample values of list1 are: [128195, 101643, 143865, 59455, 108778, 66 ...

Unraveling Traceback Errors in Python using Selenium WebDriver

Exploring the world of selenium webdriver for the first time is proving to be quite a challenge. After updating to Python 3.6 and reinstalling selenium, I attempted to open a basic webpage, only to encounter errors right off the bat. Here's the code s ...

Error: The 'charmap' codec is having trouble encoding a character which is causing issues

Before anyone criticizes me for asking the same question multiple times, I want to clarify that I have tried various suggestions from different threads, but none of them have effectively solved my issue. import json def parse(fn): results = [] wit ...

Learn the steps to automate clicking on the "next" button using Selenium or Scrapy in Python

While attempting to gather data from flipkart.com using scrapy, I successfully collected everything except for navigating to the next page. Initially, I attempted to use scrapy followed by selenium. Interestingly, a class contains two links - one for the p ...

Pseudonymic user employing hg transformation

I currently have a duplicate mercurial repository and a subversion repository that I have checked out. During the checkout of the subversion repo, I opted to save my password as plain text. My goal is to import the mercurial repo into subversion using th ...