ImportError while running "Flask run app.py" but if I run "python3 app.py" then there is no import error and works fine - python-3.x

from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from transformers import pipeline
#import transformers
app = Flask(__name__)
api = Api(app)
summarizer = pipeline("summarization", model='facebook/bart-large-cnn' )#t5-large
print("summarizer loaded")
class Summary(Resource):
def post(self):
# write what to do for post request and Add class
#Load the data
postedData = request.get_json()
#Validate the data
news = postedData['news']
summary_extractive = summarizer(news,min_length=90, max_length = 120)
#make json and return
retJSON = {
'Message': summary_extractive[0]['summary_text'],
'word_count': len(summary_extractive[0]['summary_text'].split()),
'Status Code': 200,
}
return jsonify(retJSON)
api.add_resource(Summary, '/get_summary')
if __name__ == '__main__':
app.run(debug=True)#host='0.0.0.0'
Error while running with flask run:
from transformers import pipeline
ImportError: cannot import name 'pipeline' from 'transformers' (unknown location)
But if I run with python3 app.py then there is no error.
I'm working in venv enviroment on macOS.
In pip list I'm able find the missing module transformer.

I have faced similar issue which is causes due to old version of pip. Follow the below step to resolved the issue:
upgrade your pip version use this command pip install --upgrade pip
Uninstall old version of transformer pip uninstall transformers
install again pip install transformers
It works have a nice day

Related

MacOS: Problem with run aiosqlite for any DB

I have some ERROR:
ModuleNotFoundError: No module named 'aiosqlite'
Python 3.9 ===== FastAPI ===== SQLite ===== Databases ===== aiosqlite
Error screenshot
Dependencies screenshot
Pip List screenshot
Test project on FastAPI (including from the example: https://fastapi.tiangolo.com/advanced/async-sql-databases/)
The server won't start On Mac OS (any editor: vim, VS Code, "Pycharm", etc.)
on Linux, everything works OK
but on a MacOS I can not run any of the databases (example SQLITE)
The error is as follows: does not see "aiosqlite"! All of the requirements have been seated correct (Python 3.9.5, venv, pip, aiosqlite, sqlalchemy, databases etc. - all of this have been updated)
from typing import List
import databases
import sqlalchemy
from fastapi import FastAPI
from pydantic import BaseModel
DATABASE_URL = "sqlite:///./test.db"
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("text", sqlalchemy.String),
sqlalchemy.Column("completed", sqlalchemy.Boolean),
)
app = FastAPI()
#app.post('/')
async def root():
return {"message": "Good"}
P.S.
$ . ./env/bin/activate
$ (env) ➜ testDB2 pip list
Package Version
----------------- --------
aiosqlite 0.17.0
databases 0.4.3
fastapi 0.63.0
pip 21.1.1
pydantic 1.8.1
setuptools 56.0.0
SQLAlchemy 1.3.24
starlette 0.13.6
typing-extensions 3.10.0.0
I've had used a virtual environment venv and run my server with uvicorn by some in a couple of ways:
uvicorn main:app --reload
inside the file:
app = FastAPI()
#app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Running this command solved the issue for me:
pip install databases[sqlite]
Refer to this discussion https://github.com/encode/orm/issues/33.

Getting a ModuleNotFound error with flask in python

I installed the flask module via following command.[![cmd image][1]][1]
When I ran the following code.
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
#a = input('Enter name')
return render_template(r'form.html')
if __name__ == "__main__":
app.run(debug=True)
It gave an error.
ModuleNotFoundError: No module named 'flask'
Note:- I am not using virtualenv. And I am having my html page in templates folder
[1]: https://i.stack.imgur.com/t4XzJ.png
It seems you have installed flask on the system wide environment. To access the flask in your virtualenv, you have to get into the virtualenv directory and activate it by using following command.
source virtual_env_name/bin/activate
replace 'virtual_env_name' with the virtualenv name you created.
After that in your command line, you will get (virtual_env_name) added before. the current directory path.
Now you can install the flask framework using pip3.
pip3 install flask
Keep in mind to activate venv everytime you are using the flask.

"How to fix' ImportError: cannot import name 'SQLAlchemy'

import os
from flask import Flask
from flask_wtf import FlaskForm
import sqlalchemy
from flask_sqlalchemy import SQLAlchemy
bsdir = os.path.abspath(os.path.dirname(__file__))
# print(bsdir)
app = Flask(__name__, template_folder = 'template')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(bsdir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
class Puppy(db.Model):
pass
Traceback (most recent call last):
File "D:\PYTHON\GIT_EXC\FLASK_\flask_sqlalchemyex.py", line 5, in
from flask_sqlalchemy import SQLAlchemy File "D:\PYTHON\GIT_EXC\FLASK_\flask_sqlalchemy.py", line 4, in
from flask_sqlalchemy import SQLAlchemy ImportError: cannot import name 'SQLAlch
Try using this command
pip install flask-sqlalchemy --user
It worked for me
And If you are using PyCharm go to file
Select Invalidate caches and restart
Try to install it with these commands , (it worked for me):
pip install flask-sqlalchemy
pip3 install flask-sqlalchemy
Refer this site for Example
or
Refer the official guide site for installation
if it doesnt worked then try above commands with --user at the end of both commands
another solution maybe to install an IDE (if you are not using one) like PyCharm ; rather than a some simple text editors
First command installs package to python v2.x
Second one installs package to python 3.x
If you want to use 3.x to run your app ;then go to configuration and change it to python 3.x
Refer this for Getting Help / Development / Bug reporting
Try changing the name of your .py file. It may be causing a conflict with the flask-sqlalchemy package.
"D:\PYTHON\GIT_EXC\FLASK_\flask_sqlalchemy.py"
I faced same issue while instantiating airflow db by command
$airflow db init
error: ImportError: cannot import name 'SQLAlchemyAutoSchema'
Fixes:
Uninstall:
$pip uninstall marshmallow-sqlalchemy
Then upgrade it to version 0.24.0
$pip3 install marshmallow-sqlalchemy==0.24.0
My problem resolved and able to initialize airflow db.

Tensorflow Hub and CGI

I have installed tensorflow_hub package in python 3.6. The package can be imported correctly when I test it in python console. However, when I use it in a cgi-script an error occurs:
no module named tensorflow_hub
Source Code
#!/usr/bin/python3.6
import sys
import cgitb
import cgi
t = ''
try:
import tensorflow_hub as tf
except Exception as e:
t = str(e)
cgitb.enable()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
result = dict()
result['data'] = t
sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")
Could you explain me which is the problem? I tested other packages (e.g. tensorflow) but I hadn't any issue.
Edit
To install the package:
pip3 install tensorflow-hub
which pip3
/usr/bin/pip3
To answer my question giving feedback to others with similar problem:
The tensorflow_hub was in the ~/.local/lib/python3.6/site-packages/ where the cgi hasn't got access.
To find the location:
pip3 show tensorflow_hub
I observed that all the other packages where in /usr/local/lib/python3.6/dist-packages/
So, I moved the package from the first location to the second.
This helped me:
Why can't python find some modules when I'm running CGI scripts from the web?

Django-registration ImportError: No module named signals

I am trying to write a signal listener for django-registration and I am getting the import error: no module named signals. But I could import registration.
Here is my code
from django.contrib.auth import login
from registration.signals import user_registered
def user_registered_handler(sender, **kwargs):
"""signal intercept for user_login"""
user = kwargs['user']
user.is_active = True
user.save()
login(user)
user_registered.connect(user_registered_handler)
-- Thanks in advance.
Try using a specific path to version 0.8. I noticed that using easy install and pip installed 0.7 which does not have signals.py.
Using pip:
$ pip install -Iv https://bitbucket.org/ubernostrum/django-registration/downloads/django-registration-0.8-alpha-1.tar.gz

Resources