Local Variable Referenced Before Assignment Python Error An Integer

When Python parses the body of a function definition and encounters an assignment such as

Python interprets as a local variable by default. If you do not wish for it to be a local variable, you must put

in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes a global variable everywhere in the function.

Without the global statement, since is taken to be a local variable, when Python executes

Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds is undefined. Hence the error.

The shortest way to patch up the code is to add to the beginning of . The nicer way is to use a class:

The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand.

By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.

I get this error in Jinja2 when I click my Follow button: UnboundLocalError: local variable 'to_user' referenced before assignment

File "/home/treehouse/workspace/app.py", line 132, in follow return redirect(url_for('stream', username=to_user.username))

app.py:

fromflaskimport(Flask,g,render_template,flash,redirect,url_for)fromflask.ext.bcryptimportcheck_password_hashfromflask.ext.loginimport(LoginManager,login_user,logout_user,login_required,current_user)importformsimportmodelsDEBUG=TruePORT=8000HOST='0.0.0.0'app=Flask(__name__)app.secret_key='auoesh.bouoastuh.43,uoausoehuosth3ououea.auoub!'login_manager=LoginManager()login_manager.init_app(app)login_manager.login_view='login'@login_manager.user_loaderdefload_user(userid):try:returnmodels.User.get(models.User.id==userid)exceptmodels.DoesNotExist:returnNone@app.before_requestdefbefore_request():"""Connect to the database before each request."""g.db=models.DATABASEg.db.connect()g.user=current_user@app.after_requestdefafter_request(response):"""Close the database connection after each request."""g.db.close()returnresponse@app.route('/register',methods=('GET','POST'))defregister():form=forms.RegisterForm()ifform.validate_on_submit():flash("Yay, you registered!","success")models.User.create_user(username=form.username.data,email=form.email.data,password=form.password.data)returnredirect(url_for('index'))returnrender_template('register.html',form=form)@app.route('/login',methods=('GET','POST'))deflogin():form=forms.LoginForm()ifform.validate_on_submit():try:user=models.User.get(models.User.email==form.email.data)exceptmodels.DoesNotExist:flash("Your email or password doesn't match!","error")else:ifcheck_password_hash(user.password,form.password.data):login_user(user)flash("You've been logged in!","success")returnredirect(url_for('index'))else:flash("Your email or password doesn't match!","error")returnrender_template('login.html',form=form)@app.route('/logout')@login_requireddeflogout():logout_user()flash("You've been logged out! Come back soon!","success")returnredirect(url_for('index'))@app.route('/new_post',methods=('GET','POST'))@login_requireddefpost():form=forms.PostForm()ifform.validate_on_submit():models.Post.create(user=g.user.id,content=form.content.data.strip())flash("Message posted! Thanks!","success")returnredirect(url_for('index'))returnrender_template('post.html',form=form)@app.route('/')defindex():stream=models.Post.select().limit(100)returnrender_template('stream.html',stream=stream)@app.route('/stream')@app.route('/stream/<username>')defstream(username=None):template='stream.html'ifusernameandusername!=current_user.username:user=models.User.select().where(models.User.username**username).get()stream=user.posts.limit(100)else:stream=current_user.get_stream().limit(100)user=current_userifusername:template='user_stream.html'returnrender_template(template,stream=stream,user=user)@app.route('/follow/<username>')@login_requireddeffollow(username):try:to_user=models.User.get(models.User.username*username)exceptmodels.DoesNotExist:passelse:try:models.Relationship.create(from_user=g.user._get_current_object(),to_user=to_user)exceptmodels.IntegrityError:passelse:flash("Youre now following {}!".format(to_user.username),"success")returnredirect(url_for('stream',username=to_user.username))@app.route('/unfollow/<username>')@login_requireddefun_follow(username):try:to_user=models.User.get(models.User.username*username)exceptmodels.DoesNotExist:passelse:try:models.Relationship.get(from_user=g.user._get_current_object(),to_user=to_user).delete_instance()exceptmodels.IntegrityError:passelse:flash("You've unfollowed {}!".format(to_user.username),"success")returnredirect(url_for('stream',username=to_user.username))if__name__=='__main__':models.initialize()try:models.User.create_user(username='kennethlove',email='kenneth@teamtreehouse.com',password='password',admin=True)exceptValueError:passapp.run(debug=DEBUG,host=HOST,port=PORT)

forms.py

fromflask_wtfimportFormfromwtformsimportStringField,PasswordField,TextAreaFieldfromwtforms.validatorsimport(DataRequired,Regexp,ValidationError,Email,Length,EqualTo)frommodelsimportUserdefname_exists(form,field):ifUser.select().where(User.username==field.data).exists():raiseValidationError('User with that name already exists.')defemail_exists(form,field):ifUser.select().where(User.email==field.data).exists():raiseValidationError('User with that email already exists.')classRegisterForm(Form):username=StringField('Username',validators=[DataRequired(),Regexp(r'^[a-zA-Z0-9_]+$',message=("Username should be one word, letters, ""numbers, and underscores only.")),name_exists])email=StringField('Email',validators=[DataRequired(),Email(),email_exists])password=PasswordField('Password',validators=[DataRequired(),Length(min=2),EqualTo('password2',message='Passwords must match')])password2=PasswordField('Confirm Password',validators=[DataRequired()])classLoginForm(Form):email=StringField('Email',validators=[DataRequired(),Email()])password=PasswordField('Password',validators=[DataRequired()])classPostForm(Form):content=TextAreaField("What's up?",validators=[DataRequired()])

models.py

importdatetimefromflask.ext.bcryptimportgenerate_password_hashfromflask.ext.loginimportUserMixinfrompeeweeimport*DATABASE=SqliteDatabase('social.db',threadlocals=True)classUser(UserMixin,Model):username=CharField(unique=True)email=CharField(unique=True)password=CharField(max_length=100)joined_at=DateTimeField(default=datetime.datetime.now)is_admin=BooleanField(default=False)classMeta:database=DATABASEorder_by=('-joined_at',)defget_posts(self):returnPost.select().where(Post.user==self)defget_stream(self):returnPost.select().where((Post.user==self))deffollowing(self):"""The users that we are following."""return(User.select().join(Relationship,on=Relationship.to_user).where(Relationship.from_user==self))deffollowers(self):"""Get users following the current user"""return(User.select().join(Relationship,on=Relationship.from_user).where(Relationship.to_user==self))@classmethoddefcreate_user(cls,username,email,password,admin=False):try:withDATABASE.transaction():cls.create(username=username,email=email,password=generate_password_hash(password),is_admin=admin)exceptIntegrityError:raiseValueError("User already exists")classPost(Model):timestamp=DateTimeField(default=datetime.datetime.now)user=ForeignKeyField(rel_model=User,related_name='posts')content=TextField()classMeta:database=DATABASEorder_by=('-timestamp',)classRelationship(Model):from_user=ForeignKeyField(User,related_name='relationships')to_user=ForeignKeyField(User,related_name='related_to')classMeta:database=DATABASEindexes=((('from_user','to_user'),True),)definitialize():DATABASE.connect()DATABASE.create_tables([User,Post,Relationship],safe=True)DATABASE.close()

Also this may be related or a separate bug, but my user's "post" is just a bunch of code:

https://www.dropbox.com/s/ibs2v3fhxp4awr2/Screenshot%202015-12-07%2018.27.55.png?dl=0

0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *