Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Help needed serializing

hello guys im having a hard time serializing sqlalchemy object type AppenderBaseQuery

This is my model:

class Follow(db.Model):

__tablename__ = 'follow'

follower_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)

def __repr__(self):
return f'follower: {self.follower_id}, followed: {self.followed_id}'


class User(db.Model):

__tablename__ = 'user'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True)
email = db.Column(db.String(100))
password = db.Column(db.Binary)
profilepic = db.Column(db.String)
timecreated = db.Column(db.DateTime)

#picture = db.relationship('Picture', backref='owner', lazy='dynamic')
comment = db.relationship('Comment', backref='user', lazy='dynamic')
post = db.relationship('Post', backref='user', lazy='dynamic')

followed = db.relationship('Follow', foreign_keys=[Follow.follower_id],
backref=db.backref('follower', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
followers = db.relationship('Follow',
foreign_keys=[Follow.followed_id],
backref=db.backref('followed', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')

def follow(self, user):
if not self.is_following(user):
f = Follow(follower=self, followed=user)
db.session.add(f)
db.session.commit()


def unfollow(self, user):
f = self.followed.filter_by(followed_id=user.id).first()
if f:
db.session.delete(f)

def is_following(self, user):
return self.followed.filter_by(followed_id=user.id).first() is not None

def is_followed_by(self, user):
return self.followers.filter_by(follower_id=user.id).first() is not None

def selfFollowing(self):
#Allow user in session to follow him/herself to allow posts of user in session
#to be able to render own posts if wanted

u = Follow.query.filter_by(followed_id=self.id).first()
if u is None:
#self.followers.append(Follow(follower=self))
f = Follow(follower_id=self.id, followed_id=self.id)
db.session.add(f)
db.session.commit()

@property
def followed_posts(self):
return Post.query.join(Follow, Follow.followed_id == Post.user_id)\
.filter(Follow.follower_id == self.id).order_by(Post.timestamp.desc())

@property
def followed_posts_to_json(self):
l = []
for p in self.followed_posts:
obj = p.timestamp
date = self.datetime_serialized(obj)
comm = p.comment.comment
c = p.commentList(comm)

json = {

'post_id': p.id,
'posts': p.post,
'time': date,
'userpic': p.postowner.profilepic,
'username': p.username,
'picposted': p.picture,
'comment': c
}
l.append(json)

return l

def post_to_json(self):
l = []
for p in self.post.all():

obj = p.timestamp

j = {

'id': p.id,
'post': p.post,

}

l.append(j)
return l

@staticmethod
def datetime_serialized(obj):
i
Quick reddit account migration script

Hey everyone, I haven't touched python in a while so I wanted to program a little script to migrate to a new account and wipe the old one (I'm a little paranoid about anonymity). Figured I would post it in hopes of some tips or critique, and maybe someone will find it useful. I also apologize if this isn't the right sub for this, didn't know where to post

import praw
#Account Migration Script
#By:/u/letmelive123
#Date:6/24/2017

#Warning! Using this script will entirely wipe the parent Account.
#To use input accounts and body to replace comments with
#parentAcc is the account being wiped
#secAcc is the account you are moving to
#body is the text that will replace all comments on parentAcc


#This function will transfer new multireddits to the target account.
#Note:We convert 'multi' to str and partition it to extract the multireddit name
#This is because parentAcc.user.multireddits() returns a list of paths to multireddits
def transferMultis():
for multi in parentAcc.user.multireddits():
s = str(multi)
parentAcc.multireddit(name=s.partition("/m/")[2], redditor=parentAcc.user.me()).update(visibility='public')
secAcc.multireddit(name=s.partition("/m/")[2], redditor=parentAcc.user.me()).copy(display_name=None)
parentAcc.multireddit(name=s.partition("/m/")[2],redditor=parentAcc.user.me()).delete()


#This function will transfer new multireddits to the target account.
def transferSubs():
for sub in parentAcc.user.subreddits():
s = str(sub)
secAcc.subreddit(s).subscribe()
parentAcc.subreddit(s).unsubscribe()

#This function will clean the comments of parentAcc.
def wipeComments(body):
for comment in parentAcc.redditor(name=str(parentAcc.user.me())).comments.top(time_filter='all'):
comment.edit(body)


###WARNING###
#This Account will be wiped
###WARNING###
#Parent Account
parentAcc = praw.Reddit(client_id='',
client_secret='',
password='k',
user_agent='AccMigrate by /u/letmelive123',
username='')

#Secondary Account
secAcc = praw.Reddit(client_id='',
client_secret='',
password='',
user_agent='AccMigrate by /u/letmelive123',
username='')

#Body for replacing comments
body="Test"

print("Hello welcome to AccMigrate.")
print("Please note wiping comments does take some time.")

transferMultis()
transferSubs()
wipeComments(body) print("done")


/r/Python
https://redd.it/6j6rpp
Commands that will help you troubleshoot migrations and databases!

So, I made a mess with migrations in the last week, and I learnt a bunch of things, just wanted to share those!

​

**the basic ones:**

Don't run makemigrations on production, run on development and then push and pull

python manage.py makemigrations
python manage.py migrate

​

**for inspection:**

when you make a mess the first thing you should do is understand the current state of your db, I didn't know about these and that cost me a lot. When you understand the state of your db well, you can use --fake to manipulate stuff well.

python manage.py showmigrations
python manage.py dbshell psql
#after the psql command you can use the following to inspect individual tables:
\d {{app}}_{{model | lower}}
python manage.py inspectdb #to understand the schema

​

**for manipulation without deleting/adding stuff in the migrations db:**

***WARNING*** \- Read a lot about this and be extremely careful with what you are doing here, this has potential to massively waste your time and ruin your week if you don't understand what you are doing! (Learn from my mistakes) If you absolutely have to use this,

/r/django
https://redd.it/spa8vo