Пример #1
0
def update_blog_page():
    user_info = request.cookies.get('user_info')
    user_name = request.cookies.get('user_name')
    user_status = request.cookies.get('log_status')
    homecookie = {
        'user_info': user_info,
        'user_name': user_name,
        'log_status': user_status
    }
    checkresult = parse_signed_cookie(homecookie)
    if checkresult:
        ctx.blogname = request.form['name']
        ctx.blogsummary = request.form['summary']
        ctx.blogcontent = request.form['content']
        print 'ctx:', ctx.blogname
        u = MyModel.User()
        user = u.select_one('id', user_name)
        b = MyModel.Blog(user_id=user_name,
                         user_name=user['name'],
                         name=ctx.blogname,
                         summary=ctx.blogsummary,
                         content=ctx.blogcontent,
                         id=next_id(),
                         created_at=time.time())
        b.insert_one()
        return redirect(url_for('home'))
    else:
        return redirect(url_for('authenticate_page'))
Пример #2
0
class User(Model):
    __table__ = 'User'

    id = StringField('id', default=next_id())
    email = StringField('email', upable=False)
    password = StringField('password')
    admin = BooleanField('admin')
    name = StringField('name')
    image = StringField('image')
    created_at = FloatField('create_at', default=time.time())
Пример #3
0
class Comment(Model):
    __table__ = 'Comment'

    id = StringField('id', default=next_id())
    blog_id = StringField('blog_id')
    user_id = StringField('user_id')
    user_name = StringField('username')
    user_image = StringField('user_image')
    content = TextField('content')
    created_at = FloatField('create_at')
Пример #4
0
class User(Model):
    __table__ = 'user'

    id = IntegerField(primary_key=True, updatable=False, ddl='bigint(20)')
    uid = IntegerField(default=db.next_id(), updatable=False, ddl='bigint(20)')
    email = StringField(ddl='varchar(50)')
    name = StringField(ddl='varchar(50)')
    password = StringField(ddl='varchar(10)')
    admin = IntegerField(ddl='tinyint(4)', default=0)
    create_time = TimeField()
Пример #5
0
class Blog(Model):
    __table__ = 'Blog'

    id = StringField('id', primary_key=True, default=next_id())
    user_id = StringField('user_id', upable=False)
    user_name = StringField('use_name')
    user_image = StringField('user_image')
    name = StringField('name')
    summary = StringField('summary')
    content = TextField('content')
    created_at = FloatField('create_at', upable=False, default=time.time())
Пример #6
0
def account(action):
    """
        account handler, 
        if action == recovery, validate its zid and email and send a validate email
        if action == reset, get resetCode and return to recovery page
        if action == resetSave, save new password
    """
    if action == 'recovery':
        if request.method == 'GET':
            return render_template('recovery.html')
        if request.method == 'POST':
            zid = request.form.get('zid', '')
            email = request.form.get('email', '')
            # validate zid and email
            user = User.findByKey(zid)
            if not user:
                flash('Failed: zid doesn\'exist.')
                return render_template('recovery.html')
            # if email != user.email:
            #     flash('Failed: email was wrong.')
            #     return render_template('recovery.html')
            mail = MailUtils(email, 'MateLook Team', user.full_name)
            resetCode = next_id()
            mail.reset(zid, resetCode)
            flash('Success: vaildate email has send, pleacse check your inbox.')
            return render_template('login.html')
    if action == 'reset':
        zid = request.args.get('zid', '')
        resetCode = request.args.get('resetCode', '')
        # validate zid and resetCode
        if resetCode and zid:
            user = User.findByKey(zid)
            if not user:
                flash('Failed: zid doesn\'exist.')
                return render_template('recovery.html')
        return render_template('recovery.html', user=user)
    if action == 'resetSave':
        zid = request.form.get('zid', '')
        password = request.form.get('password', '')
        password_check = request.form.get('password_check')
        user = User.findByKey(zid)
        if password != password_check:
            flash('Failed: password doesn\'t consist.')
            return render_template('recovery.html', user=user)
        if user:
            zid_password = '******' % (zid, password)
            sha_password = hashlib.sha1(zid_password.encode('utf-8')).hexdigest()
            user.password = sha_password
            user.update()
            return redirect(url_for('login'))
    return redirect(url_for('login'))
Пример #7
0
class CRUD:
    id = db.next_id()
    data = {}
    raw_data = False

    def __init__(self):
        pass

    def setup(self):
        pass

    def on_create_entry(self):
        return {}

    def create_entry(self, data, id):
        self.data = data
        self.id = id
        base_entry = {
            "id": id,
            "self": "{}{}/{}".format(ctx.base_url, self.location, id)
        }

        custom_entry = self.on_create_entry()
        combined = dict(base_entry)
        combined.update(custom_entry)
        return combined

    def dump(self):
        data = self.data
        data["id"] = self.id
        return data

    def getAll(self):
        return myDB.getAll(self)

    def get(self, id):
        self.id = id
        return myDB.get(self)

    def post(self, data):
        self.data = data
        return myDB.add(self)

    def put(self, data, id):
        self.id = id
        self.data = data
        return myDB.update(self)

    def delete(self, id):
        self.id = id
        return myDB.delete(self)
Пример #8
0
    def post(self, data):
            
        id = db.next_id()    
        data["@context"] =  "/api/contexts/Event.jsonld"
        data["@id"] =  "/api/events/{}".format(id)
        data["@type"] =  "http://schema.org/Event"

        result = myDB.add_(id, "Event", data)
        if isinstance(result, Response):
            return result

        event_url = "{}/api/events/{}".format(ctx.base_url, id)
        headers = hydra.LINK_HEADER
        headers["location"] = event_url
        headers["content-location"] = event_url
        return ctx.success(data, 201, headers=headers)
def generic_post_action(data, entry_context, entry_id, entry_type, db_name):
    current_id = db.next_id()

    entry_url = "{}{}".format(ctx.base_url,
                              entry_id.replace("<id>", current_id))
    data["@context"] = entry_context
    data["@id"] = entry_url
    data["@type"] = entry_type

    result = myDB.add_(current_id, db_name, data)
    if isinstance(result, Response):
        return result

    headers = hydra.LINK_HEADER
    headers["location"] = entry_url
    headers["content-location"] = entry_url
    return ctx.success(data, 201, headers=headers)
Пример #10
0
 def reset(self, zid, code=next_id()):
     content = 'Please click the url to reset your password.\n\n'
     content += 'http://%s:%s/account/reset?zid=%s&&resetCode=%s' % (
         _URL_, _PORT_, zid, code)
     # print(content)
     msg = MIMEText(content)
     msg['From'] = self._format_addr('{} <{}>'.format(
         self.sender, self.from_addr))
     msg['To'] = self._format_addr('{} <{}>'.format(self.receiver,
                                                    self.to_addr))
     msg['Subject'] = Header('From matelook ... ', 'utf-8').encode()
     server = smtplib.SMTP("smtp.gmail.com", 587)
     server.ehlo()
     server.starttls()
     server.login(self.from_addr, self.password)
     server.sendmail(self.from_addr, self.to_addr, msg.as_string())
     server.close()
Пример #11
0
def comment_submit():
    user_info = request.cookies.get('user_info')
    user_name = request.cookies.get('user_name')
    user_status = request.cookies.get('log_status')
    homecookie = {
        'user_info': user_info,
        'user_name': user_name,
        'log_status': user_status
    }
    checkresult = parse_signed_cookie(homecookie)
    if checkresult:
        comment = request.form['comment']
        blog_id = request.form['blog_id']
        c = MyModel.Comment(id=next_id(),
                            blog_id=blog_id,
                            user_id=user_name,
                            content=comment,
                            created_at=time.time())
        c.insert_one()
        return redirect(url_for('home'))
Пример #12
0
 def load_folder(self):
     '''
     Get ebooks from a folder and add them to database.
     '''
     path=self.EntryFolder.get()
     if not isdir(path):
         print 'The folder is not valid!'
         return 1
     logger.info('Database loads folder : %s' % path)
     print path
     PATH,FileName,EXT=load_folder(path)
     
     for i in range(len(PATH)):            
         book1 = dict(id=db.next_id(), name=FileName[i], path=PATH[i]+FileName[i]+'.'+EXT[i],
                      description=FileName[i], score=3, tags='',last_modified=time.time())
         db.insert('books', **book1)
     logger.info('Database added %d books.' % len(PATH))
     #add a progress bar here
     self.set_default_display()
     
     #to do: update a folder when new books added
     pass
Пример #13
0
        server.login(self.from_addr, self.password)
        server.sendmail(self.from_addr, self.to_addr, msg.as_string())
        server.close()

    def notificaion(self):
        content = 'Hello {}, you hava a new notification, please check your account.'.format(
            self.receiver)
        msg = MIMEText(content)
        msg['From'] = self._format_addr('{} <{}>'.format(
            self.sender, self.from_addr))
        msg['To'] = self._format_addr('{} <{}>'.format(self.receiver,
                                                       self.to_addr))
        msg['Subject'] = Header('Comment Notification', 'utf-8').encode()
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(self.from_addr, self.password)
        server.sendmail(self.from_addr, self.to_addr, msg.as_string())
        server.close()


if __name__ == '__main__':
    mail = MailUtils('*****@*****.**', 'changxun', 'vane')
    print('begin')
    # mail.send()
    print('end')
    print(next_id())
    print()
    print(_URL_)
    mail.reset('z5006334')
Пример #14
0
# Start mocking

myDB.data["/locations"] = {}
myDB.data["/events"] = {}
myDB.data["/authors"] = {}



# ---------------------------------------------------------------------------------
# Mock location resource

location_entries = [(index, row) for index, row in cities_df.iterrows()]

location_ids = []
for index, row in location_entries[:10]:
    id = db.next_id()
    location_ids.append(id)
    myDB.add_(id, "locations", {
        "@context": "/api/contexts/Location.jsonld",
        "@type": "http://schema.org/City",
        "name": row["city"],  
        "latitude": row["lat"],
        "longitude": row["lng"],
        "population": row["pop"],
        "countryAddress": row["country"],
        "state": row["province"],
        "@id": "http://localhost:5000/api/locations/{}".format(id)
    })