I'm creating a simple flask app. I'm using blueprints to provide views and OpenID for login. I have faced the problem when I try to import created OpenID object to the file with the views interpreter throws an Import Error.
Traceback (most recent call last):
File "/.../ProgList/ProgList.py", line 11, in <module>
from views_admin import views as views_a
File "/.../ProgList/views_admin.py", line 4, in <module>
from ProgList import open_id
File "/.../ProgList/ProgList.py", line 11, in <module>
from views_admin import views as views_a
ImportError: cannot import name 'views'
ProgList.py
# importing VIEWS
from views import views
from views_admin import views as views_a
...
open_id = OpenID(app, 'temp_dir_path')
views_admin.py
from ProgList import open_id
...
#views.route("/login", methods=["GET", "POST"])
#open_id.loginhandler
def login():
I have been struggling this problem for hours and couldn't find an answer.
Thank you very much for help.
In ProgList, you import views_admin, in views_admin, you import ProgList. This cannot be resolved. The typical approach here is to outsource something to a third file which both can safely access without interfering with each other. From the looks of it, you might want to move open_id into a different file.
Related
noob question series...
I am a new learner of python, recently want to create a small python application that can collect photos from flickr based on different search input. (eg: if i input "dog", it will download all dog images from flickr)
I did some research online and notice that flickr API might be the best way and the method flickr.photos.getSizes should be the one I need to use.
However, I have few stupid questions when coding:
I have applied my key and secret for flickr API, I just don't know what to do next with flickr.photos.getSizes in python to download photos. Like, how to call this method in python? (and I noticed required arguments for this method are keys and photo_id, how to get photo_ids based on search input "dog")
Then I followed a tutorial from https://github.com/alexis-mignon/python-flickr-api/wiki/Tutorial but when I imported flickr_api I got error message:
Could not load all modules
<class 'ImportError'> No module named 'objects'
Traceback (most recent call last):
File "D:/Agfa/Projects/Image/flickr.py", line 2, in <module>
import flickr_api
File "D:\Application\Anaconda3\lib\site-packages\flickr_api\__init__.py", line 32, in <module>
from auth import set_auth_handler
ImportError: cannot import name 'set_auth_handler'
Then I took a look at the _ init _.py:
try:
from objects import *
import objects
import upload as Upload
from upload import upload, replace
except Exception as e:
print "Could not load all modules"
print type(e), e
from auth import set_auth_handler
from method_call import enable_cache, disable_cache
from keys import set_keys
from _version import __version__
Seems like this library does not support python 3 but I don't know what to do. (I cannot install methond_call, keys, _version on my python 3) guess I will use flickrapi
Thank you so much for your time and again thanks in advance.
I think I finally got the proper way to use FlickrAPI:
there are many ways but I figured out 2:
def flickr_walk(keyward):
count = 0
photos = flickr.walk(text=keyward,
tag_mode='all',
tags=keyward,
extras='url_c',
per_page=100)
for photo in photos:
try:
url=photo.get('url_c')
urllib.request.urlretrieve(url, path+'\\' + str(count) +".jpg")
except Exception as e:
print('failed to download image')
flickr.walk uses Photos.search API, I can use the API directly as well:
def flickr_search(keyward):
obj = flickr.photos.search(text=keyward,
tags=keyward,
extras='url_c',
per_page=5)
for photo in obj:
url=photo.get('url_c')
photos = ET.dump(obj)
print (photos)
Remember to get the key and secret first:
api_key = 'xxxxxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxx'
flickr=flickrapi.FlickrAPI(api_key,api_secret,cache=True)
I dont have any clue on the why/how. If you want to use the flickr_api module with python3.5+, you need to fix the Imports, like I did below:
try:
from objects import *
import objects
import upload as Upload
from upload import upload, replace
except Exception as e:
#print "Could not load all modules"
print( type(e), e)
from .auth import set_auth_handler
from .method_call import enable_cache, disable_cache
from .keys import set_keys
from ._version import __version__
After this edit, it fails with another Import Error on:
>>> import flickr_api
<class 'SyntaxError'> invalid syntax (method_call.py, line 50)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/krysopath/.local/lib/python3.5/site-packages/flickr_api/__init__.py", line 32, in <module>
from .auth import set_auth_handler
File "/home/krysopath/.local/lib/python3.5/site-packages/flickr_api/auth.py", line 43, in <module>
import urlparse
ImportError: No module named 'urlparse'
So you can fix this by yourself, if you want to, by just walking along the Import Errors and adding a dot to convert them into absolute Imports, that dont fail.
I guess, if you want to use this modul you have to fix it first... and have an unknown return. So if you didnt already invested heavily, it might be more effective to use that other module.
I am trying to run an application that uses django (version 1.6.5) rest framework ( python version 3.4.5 ) .However I am getting the Import error "cannot import name DurationField".How do I resolve this error ?
File "/usr/src/app/Lab/models.py", line 8, in <module>
from Lab import logic, common <br>
File "/usr/src/app/Lab/logic.py", line 16, in <module>
from Rest import viewsAppComm <br>
File "/usr/src/app/Rest/viewsAppComm.py", line 7, in <module>
from rest_framework.response import Response <br>
File "/usr/local/lib/python3.4/site-packages/rest_framework/response.py", line 13, in <module>
from rest_framework.serializers import Serializer
File "/usr/local/lib/python3.4/site-packages/rest_framework/serializers.py", line 19, in <module>
from django.db.models import DurationField as ModelDurationField <br>
ImportError: cannot import name 'DurationField'
DurationField was added in Django 1.8. You are using Django 1.6, hence the error.
Your options are to upgrade (which is a good idea if you can, because Django 1.6 has reached end of life quite a while ago) or to downgrade to an older version of Django Rest Framework (the version you currently have is not compatible with Django 1.6).
You may also be able to install the third-party django-duration-field app and then import it with:
from durationfield.db.models.fields.duration import DurationField
... but from the stack trace you posted it looks like it is DRF that is trying to import the model.
Problem Description
Getting error message when trying to start Flask.
Traceback (most recent call last):
File "./run.py", line 3, in <module>
from app import app
File "/home/xxxxxx/xxxx.xxxxxxx.com/ClientTracker/app/__init__.py", line 13, in <module>
app.register_blueprint(admin)
File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 65, in wrapper_func
return f(self, *args, **kwargs)
File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 958, in register_blueprint
if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'
This is a migration from a simpler hierarchy implementing Blueprints. I'm splitting out the function of the frontend and the admin panel.
I built this step by step and had both sides working fine.
Started migrating (functions and routes). After moving some code, I started getting an error message (basically the same as above, but different line).
Troubleshooting
Searched through related posts on stackO
Initially it was complaining about the second route statement I had. I
started removing code (rolling back) to what I (thought was) a known
good state. However I continued to have issues.
I have it down to the minimum code I believe I need but still getting
errors.
If I remove the registration in the init.py file, the frontend works
perfectly.
Code
#ClientTracker/run.py
#!env/bin/python
from app import app
app.run(host='0.0.0.0', port=8080, debug=False)
#ClientTracker/app/__init__.py
# Import flask and template operators
from flask import Flask, render_template
# Define the WSGI application object
app = Flask(__name__)
# Import a module / component using its blueprint handler variable (mod_auth)
#from app.mod_auth.controllers import mod_auth as auth_module
from app.admin.views import admin
from app.client.views import client
# Register blueprint(s)
app.register_blueprint(admin)
app.register_blueprint(client)
#ClientTracker/app/admin/views.py
from flask import render_template, request, Blueprint
from app import app
import MySQLdb
import datetime
admin = Blueprint(
'admin',
__name__,
url_prefix='/admin',
template_folder='templates',
static_folder='static'
)
#admin.route('/')
def admin():
return "ok"
I'm out of ideas.
Ok, so as seems to happen, I spend an hour looking, another 15 mins composing a question and then after I hit post, I find the answer.
I found a post (https://github.com/pallets/flask/issues/1327) that had the answer.
Basically, you cannot have a function name with the same name as your Blueprint name. Seems obvious now, but certainly stumped me for a while.
In thinking about it, my original "working" state had a dummy function name serving the '/'. When I rolled back, I didn't roll back far enough.
Replaced def admin(): with def admin1(): (will fix this better in prod) and all worked.
I hope this post helps someone else. Please still feel free to comment. As always, the group is always smarter than the individual. Lastly, thanks for reading this far. :-)
Your blueprint name is same with your function name, try to rename the function name instead.
Note that the blue print name and the function name can not be the same.
Make use if this tutorial to learn more about Blueprints, https://realpython.com/flask-blueprint/
I know this question has been asked countless times here, but I've been stuck with this problem for a long time and have not been able to find a solution online.
I have an import cycle, and here is the stack trace:
Traceback (most recent call last):
File "openldap_lookup.py", line 2, in <module>
import pure.directory_service.ds_lookup as dsl
File "/home/myname/purity/tools/pure/directory_service/ds_lookup.py", line 8, in <module>
import pure.authorization.auth as auth
File "/home/myname/purity/tools/pure/authorization/auth.py", line 16, in <module>
import auth_unix as auth_impl
File "/home/myname/purity/tools/pure/authorization/auth_unix.py", line 17, in <module>
import pure.directory_service.ad_lookup as ad_lookup
File "/home/myname/purity/tools/pure/directory_service/ad_lookup.py", line 1, in <module>
import pure.authorization.auth as auth
AttributeError: 'module' object has no attribute 'auth'
I import modules only; I avoid the from <module> import <class> and from <module> import <method>
I tried to reproduce the error locally, but python has no complaints. These are the local test files:
openldap_lookup.py
import ds_lookup
def openldap_foo():
print ds_lookup.ds_foo
print 'openldap_lookup importing ds_lookup'
ds_lookup.py
import auth as au
def ds_foo():
print au.auth_foo
print 'ds_lookup importing auth'
auth.py
import auth_unix
def auth_foo():
print auth_unix.auth_unix_foo
print 'auth importing auth_unix'
auth_unix.py
import ad_lookup
def auth_unix_foo():
print ad_lookup.ad_foo
print 'auth_unix importing ad_lookup'
ad_lookup.py
import auth as au
def ad_foo():
print au.auth_foo
print 'ad_lookup importing auth'
But python doesn't complain:
myname#myname-mbp:~/cycletest$ python openldap_lookup.py
ad_lookup importing auth
auth_unix importing ad_lookup
auth importing auth_unix
ds_lookup importing auth
openldap_lookup importing ds_lookup
myname#myname-mbp:~/cycletest$
I am not a python expert, but I understand that an import cycle is causing the error. But why doesn't the same error occur with the small test files? When is an import cycle legal in python and when is it not? What can I do to resolve this?
I would greatly appreciate any help from the python experts out there.
Since many are bound to ask, why do I have this cycle in the first place?
Well, openldap_lookup and ad_lookup both contain subclasses of a base class in ds_lookup. ds_lookup requires constants from auth. auth requires auth_unix as an implementation, and auth_unix in turn calls the implementations openldap_lookup and ad_lookup.
I would love to move the constants out from auth and remove the cycle, but this code is part of a large git repo where hundreds of files depend on the constants and methods in auth, and I would like to avoid having to refactor all of them if possible.
Actually, you're not just importing modules -- you're importing modules from packages, and your test case doesn't actually reflect this.
I think the problem is that in your first import of pure.authorization.auth, the interpreter is still building the pure.authorization module (it hasn't yet bound auth into pure.authorization, because it hasn't finished importing auth), so the second time it encounters this, it finds the pure.authorization module, but there is no global variable auth in it yet.
As far as breaking the cycle goes, does auth really need to import auth_unix right away, or could that be deferred until you really need an auth implementation?
I don't know if this logic is correct,
I'm trying to import a Django view in 2 different views.
I have an import chain like this:
the
a.views import b.views
b.views import c.views
c.views import d.views
and
d.views import b.views
but when I reach the last step I get an ImportError.
If I put a comment in d.views avoiding the import of b.views, it works.
I'm new with Django, can somebody help me?
If I use in a.views and in d.views the syntax
from b.views import *
it works, but.. the code is not so readable.
If I use
from b.views import my_func
it doesn't work!
This is the error from django shell:
>>> import maps.views
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/save/sites/myblog/maps/views.py", line 19, in <module>
from places.views import *
File "/Users/save/sites/myblog/places/views.py", line 22, in <module>
from posts.views import *
File "/Users/save/sites/myblog/posts/views.py", line 31, in <module>
from maps.views import render_map_geoloc
ImportError: cannot import name render_map_geoloc
Its because of cyclic dependency or circular reference.
b depends on c
c depends on d
d depends on b #which depends on c
Not sure for what purpose you are using. But you do explicit import to that function, and right above where its been used.
Looking at the error you are getting, it might be because of some dependency expected for d is coming from b so if you from b.views import *, it gets you that dependency. But if you import specific view (my_func), its missing that dependency.
Some more details you can find on SO answer thread - Django App Dependency Cycle