The image in my Flask app has not been loading, when I view the page source it shows src="/static/profile_pics/c1a7ec356936a3db.jpg", when I changed it to src="/static/profile_pics/default.jpg", it showed the image , then I tried querying my database then realized that the default image is c1a7ec356936a3db.jpg instead of default.jpg
>>> from flaskblog.models import User
>>> user = User.query.first()
>>> user
User('fortunenwankwo_','therealfortune1#gmail.com','c1a7ec356936a3db.jpg')
this is my models.User file
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref="author", lazy=True)
this is my account route file
#app.route("/account", methods=['GET', 'POST'])
#login_required
def account():
image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
return render_template("account.html", title="Account", image_file=image_file, form=form)
The main question is how can I change my default image to default.jpg instead of c1a7ec356936a3db.jpg, is it possible for me to change it by querying my models file in the terminal?
ok so I realized it was just for that user , so please how can I change it?
After I discovered that the problem was just one account , I deleted the account
Related
I'm wondering what the best approach is to store user authentication data in a neo4j database with django using the inbuilt auth system.
Has anybody got any experience of doing so?
I'm imagining that it has something to do with subclassing the AbstractBaseUser and BaseUserManager but for the life of me I can't figure it out.
Would very much appreciate a code snippet if anybody has achieved this before.
Many Thanks
If you want to extend the Django User model, first check this article. It shows different ways of extending the User model. In my last workaround I needed all the information in Neo4j so I adapt my model to have the fields of the user in my model (It was a model of Student). Whenever a new student register to the app, I have a signal to react after the save (post_save) and it stores the password and the username. You can explore the Django signals here
For the model I have:
class StudentProfile(DjangoNode):
first_name = StringProperty(max_length=30)
last_name = StringProperty(max_length=150)
email = EmailProperty()
birth = DateProperty()
username = StringProperty(max_length=150, unique=True)
password = ''
For the signal:
#receiver(post_save, sender=StudentProfile, dispatch_uid='create_user_student')
def create_user_student(sender, instance, created, **kwargs):
if created:
user = User.objects.create_user(instance.username)
user.set_password(instance.password)
user.save()
#receiver(post_delete, sender=StudentProfile, dispatch_uid='delete_user_student')
def delete_user_student(sender, instance, **kwargs):
User.objects.filter(username=instance.username).delete()
Besides the main view of the StudentProfile, I have a view that uses the built-in Django authentication system:
from django.contrib.auth import authenticate, login as do_login, logout as do_logout
...
#api_view(["POST"])
def login(request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
do_login(request, user)
return Response({'login': 'ok'}, status=status.HTTP_200_OK)
return Response({'login': 'Error on credentials'}, status=status.HTTP_403_FORBIDDEN)
Many years ago I wrote an app on Google App Engine. I saved over 100,000 entries.
Here's the code I used to store it in the blob. Now I want to export all the data. Ideally, I would have prefered to download all these entries as a csv but there is no option on the backend. How can I easily download all the data I have saved over the years?
import webapp2
from google.appengine.ext import ndb
class Database(ndb.Model):
"""Models an individual user entry with email, app, and date."""
email = ndb.StringProperty()
app = ndb.StringProperty()
platform = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
class add(webapp2.RequestHandler):
def post(self):
e = self.request.get("email")
a = self.request.get("app")
p = self.request.get("platform")
b = e+', '+a+', '+p
u = Database()
u.email = e
u.app = a
u.platform = p
u.put()
Is there a way to get all of my data? I cannot output all the data on a webpage. It crashes.
Hopefully someone can help. I am building an app on Google app engine and trying to pass the credentials of an authenticated user to the push task Handler. I am using the OAuth2DecoratorFromClientSecrets library to create the decorator which seems to store the credentials for the user in the datastore. It stores it with a key name of something like "110111913122157971566". My problem is that I cant seem to find a way to figure out what that key name is so that I can retrieve it using the StorageByKeyName method from within my worker handler. The documentation I have read uses the user_id as the key name but this doesnt work for me as the credentials are not stored with the user_id as the key name, however if I hard code the key name then the code does work. I am aware that I could run the copy code from within the Submit handler but need to run it as a separate task. Below is a sample of my code, thanks for any help you can provide:
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
SCOPES =['https://www.googleapis.com/auth/drive']
decorator = OAuth2DecoratorFromClientSecrets(
os.path.join(os.path.dirname(__file__),
'client_secrets.json'),
' '.join(SCOPES)
)
class MainPage(webapp2.RequestHandler):
def get(self):
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
template_values = {'url': url,
'url_linktext': url_linktext,
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
else:
self.redirect(users.create_login_url(self.request.uri))
class Submit(webapp2.RequestHandler):
#decorator.oauth_required
def post(self):
taskqueue.add(url='/worker', params={'user_id' : users.get_current_user().user_id()})
self.response.write('<html><body>You wrote:<pre>')
self.response.write(users.get_current_user().user_id())
self.response.write('</pre></body></html>')
class Worker(webapp2.RequestHandler):
def post(self):
user_id = self.request.get('user_id')
credentials = StorageByKeyName(CredentialsModel, user_id , 'credentials').get()
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v2',http=http)
fileId = 'actual file_id of drive file here'
copied_file = {'title': 'My New Test Doc2'}
new_file = service.files().copy(fileId=fileId,body=copied_file).execute(http=http)
application = webapp2.WSGIApplication([
('/', MainPage),
('/submit', Submit),
('/worker', Worker),
(decorator.callback_path, decorator.callback_handler()),
], debug=True)
First, remove the http=decorator.http at the top level - it doesn't appear to be used and should only be used from inside the decorated method.
I'm not certain, but looking at the decorator code I think it is is keying based on the user_id(). Your code is displaying that, but the parameter you are passing to the task isn't. Try {'user_id' : users.get_current_user().user_id()}.
All,
I am in the process of learning Google App Engine / Webapp2 and i'm having trouble saving an object to the datastore, redirecting to another page/handler, then fetching that object from the datastore. Forgive me if there is an easy answer to this question. The following is a description of the code I have.
I have a base handler:
class BaseHandler(webapp2.RequestHandler):
def set_secure_cookie(self, name, val):
cookie_val = make_secure_val(val)
self.response.headers.add_header(
'Set-Cookie',
'%s=%s; Path=/' % (name, cookie_val))
def get_secure_cookie(self, name):
cookie_val = self.request.cookies.get(name)
return cookie_val and check_secure_val(cookie_val)
def login(self, user):
self.set_secure_cookie('user', str(user.name))
# Called before every request and stores user object
def initialize(self, *a, **kw):
webapp2.RequestHandler.initialize(self, *a, **kw)
username = self.get_secure_cookie('user')
self.user = username and User.by_name(str(username))
I have a Signup page which inherits from BaseHandler:
class Signup(BaseHandler):
def get(self):
# Get the page
def post(self):
has_error = False
# Extract and validate the input
if has_error:
#Re-render the form
else:
new_user = User.register(self.username, self.password, self.email)
new_user.put()
self.login(new_user)
self.redirect("/blog/welcome")
If the user is a new user, the User db.Model object is created, the user is stored to the datastore, a user cookie is set and we are redirected to the Welcome handler:
class Welcome(BaseHandler):
def get(self):
if self.user:
self.render('welcome.html', username = self.user.name)
else:
self.redirect('/blog/signup')
The intent here is that upon redirect, BaseHandler.initialize() would get called and would set self.user of the new user I just created.
Here is what I know:
- When signing up a new user, I am redirected back to the signup page.
- If I then manually navigate to /blog/welcome, the page loads correctly with the new username populated.
If I add the following logging statements into Welcome.get():
username = self.get_secure_cookie('user')
logging.info("Cookie %r obtained inside of Welcome.get().", username)
logging.info("Found user %r", User.by_name(str(username)))
The cookie is obtained for the new username but no User object is found. Again, if I navigate directly to /blog/welcome, the logs report that the cookie is obtained and the User object is found for the new user.
The User object looks like so:
def users_key(group = 'default'):
return db.Key.from_path('users', group)
class User(db.Model):
name = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty()
#classmethod
def by_name(cls, name):
u = User.all().filter('name =', name).get()
return u
#classmethod
def register(cls, name, password, email = None):
return User(parent = users_key(),
name = name,
password = password,
email = email)
Is there something about the datastore that is causing this first query to get the new user to return nothing? How should I proceed in debugging this? Is there additional reading I should do? (I have tried to provide all necessary code snippets but I can provide additional code if required.)
Just guessing, but I suspect self.username, self.password and self.email in your RequestHandler are not set to anything. I'm assuming you're getting those paramters from the request POST data, but that's not happening in the code shown.
The other potential problem is that your query is eventually consistent, and may not reflect recent changes (ie new User entity). It would be much better if you fetch the user by it's key or id with a get() call instead of a query via filter().
I have 2 Handlers. One is called MainHandler, which renders a small form to sign up a user(create an account). Upon submitting email and pwd, MainHandler checks the account doesn't exist already, validates the fields, and then creates a new User entity. Then redirects to HomeHandler (/home) and sends the user email as a URL query parameter, i.e.
"http://localhost:8000/home?email=jack#smith.com"
My question is, is that the best way to do it?? At HomeHandler there's another form that allows the user to enter an address that will be a child of the user. Using the email, I run a query to find the user. If I don't send over the user email how will HomeHandler know which user is entering the address? If I have other handlers that will receive other data to be stored and associated with the user, do I have to keep sending the user email every time? Seems like there should be a better way to do it, but I can't figure it out.
class User(db.Model):
email = db.EmailProperty()
password = db.StringProperty()
class Address(db.Model):
line1 = db.StringProperty()
line2 = db.StringProperty()
class MainHandler(webapp2.RequestHandler):
def get(self):
renders a template with a form requesting email and pwd
def post(self):
Validates form and checks account doesn't already exist
if (user doesn't already exist and both email and pwd valid):
newuser = User(email=email, password=password);
newuser.put();
self.redirect("/home?email=%s"%email)
class HomeHandler(webapp2.RequestHandler):
def get(self):
Renders another form requesting a physical address (2 lines)
def post(self):
email=self.request.get("email")
addressLine1 = self.request.get("address1")
addressLine2 = self.request.get("address2")
q = db.Query(User).filter('email =', email)#Construct query
userMatchResults = q.fetch(limit=1)#Run query
homeAddress = Address(parent=userMatchResults[0])
homeAddress.line1 = addressLine1
homeAddress.line2 = addressLine2
homeAddress.put()
app = webapp2.WSGIApplication([('/', MainHandler), ('/home', HomeHandler)], debug=True)
You do not have to redirect. You can send the second form in the post of Mainhandler.
And you can combine both handlers, If the post of the main handler can detect if the post request origin is the first or the second form. An easy way to do this, is adding a hidden input field to both forms, with the name of the form. This field will be part of the post data.
But there are many other ways to preserve the state between requests.