Flask-mongoengine: Unable to import MongoEngine From flask-mongoengine - flask

I must be missing something but I look around and couldn't find reference to this issue.
I have the very basic code, as seen in flask-mongoengine documentation.
test.py:
from flask import Flask
from flask_mongoengine import MongoEngine
When I run
python test.py
...
from flask_mongoengine import MongoEngine
ImportError: cannot import name 'MongoEngine'
Module in virtual environment contain (requirements.txt):
click==6.7
Flask==1.0.2
flask-mongoengine==0.9.5
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
mongoengine==0.15.3
pymongo==3.7.1
six==1.11.0
Werkzeug==0.14.1
WTForms==2.2.1
My interpreter is Python 3.6.5
Any help would be appreciated. Thanks.

Since your using a virtual environment did you try opening your editor from your virtual environment?
For example opening the vscode editor from command-line is "code". Go to your virtual environment via the terminal and activate then type "code" at your prompt.
terminal:~path/to/virtual-enviroment$ source bin/activate
(virtual-enviroment)terminal:~path/to/virtual-enviroment$ code
If that doesn't work I, myself, haven't used flask-mongoengine. I was nervous of any issues that would come from the abstraction of it and instead just used Mongoengine with Flask.
I'm assuming you're only using this library for connection management so if you can't solve your issue with flask-mongoengine but are still interested in using mongoengine this was my approach. ~
I would put this in a config file somewhere and import it where appropriate-
from flask import Flask
MONGODB_DB = 'DB_NAME'
MONGODB_HOST = '127.0.0.1' # or whatever your db address
MONGODB_PORT = 27017 # or whatever your port
app = Flask(__name__) # you can import app from config and it will keep its configurations
then I would connect and disconnect from the database within each HTTP request function like this-
from config import MONGO_DB, MONGODB_HOST, MONGODB_PORT
# to connect
db = connect(MONGODB_DB, host=MONGODB_HOST, port=MONGODB_PORT)
# to close connection before any returns
db.close()
Hope this helps.

I had this issue and managed to fix it by deactivating, reinstalling flask-mongoengine and reactivating the venv (all in the Terminal):
deactivate
pip install flask-mongoengine
# Not required but good to check it was properly installed
pip freeze
venv\Scripts\activate
flask run

Related

Can't import MigrateCommand from flask_migrate

I made a manage.py file for database migration in a Flask application and I get an error when trying to import MigrateCommand. I'm using PyCharm and I'm sure the package is installed.
Code:
import os
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from app import app, db
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
Error:
Cannot find reference 'MigrateCommand' in '__init__.py'
Edit:
Like Matteo Pasini answered Flask-Script is no longer supported and the best solution is to use Flask CLI. For anyone wondering what's the equivalent of the manage.py file using Flask CLI I suggest reading this short guide that explains it well:
https://medium.datadriveninvestor.com/migrating-flask-script-to-flask-2-0-cli-4a5eee269139
The MigrateCommand seems to be no longer supported: https://github.com/miguelgrinberg/Flask-Migrate/issues/407
a possible workaround could be to install an older version of Flask-Migrate, such as:
pip install Flask-Migrate==2.6.0
or switch to the Flask CLI
Flask-Script is not supported anymore. Switch to the Flask CLI or downgrade Flask-Migrate to version 2.7.0, which is the last to support Flask-Script.
pip install flask-migrate==2.7.0

Error while deploying Django app on cpanel(shared hosting)

I m new to django. I created a web with dajngo,and successfully deployed it in the server
The python app has been successfully setup and virtual environment has been setup.
but while running the web it gives me "Server Error (500)" I don't know whats the problem.
I think error is in "wsgi.py" file but i'm unable to idenify it.
My wsgi file:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'karan_web.settings')
application = get_wsgi_application()
my "passenger_wsgi.py" file is:
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'karan_web/wsgi.py')
application = wsgi.application
can someone help me with it;
Sorry for the late answer, I had figured out the as to this just forgot to post it.
As I stated in my question, the actual problem was in passenger_wsgi.py, the django server starts with the wsgi.py and act as the gate way to the Django server.
So whenever a Django project is uploaded on the hosting server, It creates a passenger_wsgi.py file and one default wsgi.py, address of which is provided in passenger_wsgi.py by default.
So we just need to change that address and provide the address of our own wsgi.py in the project
In my case it was
import os
import sys
from karan_web import wsgi
application = wsgi.application
just edit in passenger_wsgi.py the following code.
from karan_web.wsgi import application
You need to check if your code syntax is correct and running properly. If its still doesn't work try to delete and recreate your database in cpanel and check if you have made all necessary migrations, don't forget to restart your python app. If after all these it still doesn't work check if all your files have the correct file permission(766).

Set up django-celery-email for local dev

It seems the best way to send emails from the django-allauth app asynchronously is to simply install django-celery-email. But the packages warns that
This version requires the following versions:Python 2.7 and Python3.5, Django 1.11, 2.1, and 2.2 Celery 4.0
I've only been using python for several months and never encountered a situation where two python version are needed on a project. And I'm using the official recommendation of pipenv for local development. A quick google shows that it isn't possible to have two python interpreters installed in the virtual environment. Since the plugin seems so popular I wondered how others were setting it up? Apologies if I've missed something major that explains this.
A bonus answer would also take into account that I am using docker and the docker image will install the python packages like this.
RUN pipenv install --system --deploy --ignore-pipfile
Many thanks in advance.
I am pretty sure it is just inaccurate description in the project docs, so you need either python 2.7 or python >=3.5 to be installed
In the end I didn't use django-celery-email. It's easy to send the emails generated by the django-allauth app without this package.
I used these resources -
https://github.com/anymail/django-anymail/issues/79
https://docs.djangoproject.com/en/2.2/topics/email/#defining-a-custom-email-backend
Basically you do this to get it working.
In settings.py define a CustomEmailBackend -
EMAIL_BACKEND = "users.backends.CustomEmailBackend"
In a backend.py file define the backend -
from django.core.mail.backends.base import BaseEmailBackend
from .tasks import async_send_messages
class CustomEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
async_send_messages.delay(email_messages)
return len(email_messages)
And this is the task -
from django.core.mail import get_connection
from abstract_base_user.celery import app
#app.task(rety_backoff=True, serializer="pickle")
def async_send_messages(email_messages):
conn = get_connection(backend='anymail.backends.mailgun.EmailBackend')
conn.send_messages(email_messages)
The celery django app should be set up in the standard way as defined at https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
And the celery settings in the settings.py need include the pickle content type -
CELERY_ACCEPT_CONTENT = ['json', 'pickle']
Obviously you need to include your anytime settings and broker settings too. But this should be enough to get anybody started.

What changes are needed to my django app when deploying to pythonanywhere? error points to nowhere

Deploying my django website with S3 as storage which runs fine locally to pythonanywhere gives a strange error I can't google a solution for:
"TypeError: a bytes-like object is required, not 'str'"
What I'm doing wrong?
I've tried to put my environment variables out of settings.env (aws keys, secret_key, etc) ad set them directly in my settings.py app. + every suggestion I could find but it's still the same :(
here's my /var/www/username_pythonanywhere_com_wsgi.py:
# +++++++++++ DJANGO +++++++++++
# To use your own Django app use code like this:
import os
import sys
from dotenv import load_dotenv
project_folder = os.path.expanduser('~/portfolio_pa/WEB') # adjust as appropriate
load_dotenv(os.path.join(project_folder, 'settings.env'))
# assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py'
path = '/home/corebots/portfolio_pa'
if path not in sys.path:
sys.path.insert(0, path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'WEB.settings'
## Uncomment the lines below depending on your Django version
###### then, for Django >=1.5:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
###### or, for older Django <=1.4
#import django.core.handlers.wsgi
#application = django.core.handlers.wsgi.WSGIHandler()
I'd expect the website to run fine just like it does locally.
Boto library doesn't have a good Python3 support. This particular issue is known in the boto bugtracker: https://github.com/boto/boto/issues/3837
The best way of fixing this is to use boto3 which has decent Python3 support and is a generally most supported AWS SDK for Python.
The reason why it works on your local machine and doesn't work on production is that pythonanywhere setup seems to be using proxy which triggers this incompatible boto code. See the actual calling code: https://github.com/boto/boto/blob/master/boto/connection.py#L747
Your error traceback confirms this.
Unfortunately, I'm not familliar with the django-photologue, but a brief look doesn't suggest that it strongly depends on boto3. Maybe I'm wrong.
I still think that the best way is to go with boto3. As a backup strat you can fork boto with a fix for this issue and install that instead of the official one from PyPI: https://github.com/boto/boto/pull/3699

ImportError when using Haystack 2.0.0 with Django 1.5 and Gunicorn WSGI

I use django-haystack 2.0.0 to index my site, and it has been working great until I upgraded to Django 1.5 and started using the WSGI interface. If I just use the django_gunicorn command it works great, but the Django documentation "highly recommends" I use the gunicorn command.
When I start my site with the gunicorn command, Haystack throws the following error on any page load:
ImportError: cannot import name signals
I have no problems importing signals from the Django or Python shells. I use virtualenv and install all packages locally inside that environment. My wsgi.py file looks just like the default one in the django admin, except that I add the local path to the python path as such:
path = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
if path not in sys.path:
sys.path.append(path)`
Any help you could provide would be very appreciated, thank you!
I don't use gunicorn, but I had the same problem when I used the HAYSTACK_SIGNAL_PROCESSOR setting to point to a custom class that I wrote. That class imported one of my models, which eventually propagated up the import chain, to import my settings module, thus causing a circular import.
When using a setting such as HAYSTACK_SIGNAL_PROCESSOR that points to a class, make sure that class standsalone, and doesn't import either directly or indirectly the Django settings file.