Exemplo n.º 1
0
def main():
    """Main function for populating the database"""
    donors = [('Toni Morrison', random.sample(range(100, 25000), 3)),
              ('Mike McHargue', random.sample(range(100, 25000), 3)),
              ("Flannery O'Connor", random.sample(range(100, 25000), 3)),
              ('Angelina Davis', random.sample(range(100, 25000), 3)),
              ('Bell Hooks', random.sample(range(100, 25000), 3))]

    db.connect()
    db.drop_tables([Donor, Donation])
    db.create_tables([Donor, Donation])
    bcrypt = Bcrypt()

    for donor, donations in donors:
        try:
            Donor.create(name=donor,
                         email='.'.join(donor.lower().split()) + '@gmail.com',
                         password=bcrypt.generate_password_hash('password'),
                         total=sum(donations),
                         average=sum(donations) / len(donations))
        except:
            db.rollback()

    for donor, donations in donors:
        for donation in donations:
            try:
                Donation.create(donor=donor, amount=donation)
            except:
                db.rollback()
Exemplo n.º 2
0
def initdb():
    """Initialize the database."""
    click.echo('Init the db')

    print("remove database")
    if os.path.exists(DATABASE):
        os.remove(DATABASE)

    print("connect database")
    db.connect()

    print("create tables")
    db.create_tables([User, Task, Record])

    print("close database")
    db.close()
Exemplo n.º 3
0
    def __init__(self, path="./config.json", time=86400, handle=False):
        db.connect()
        db.create_tables([App, Version, Config])

        if self._first_run():
            logging.debug("[+] - First run")
            logging.debug("[+] - Loading config")
            self.config = self._read_config(path)
            logging.debug("[+] - Saving config")
            self._save_config()
        else:
            logging.debug("[+] - Restoring config from database")
            self.config = self._get_config().config

        self.urls = self.config["apps"]
        self.whitelist = self.config["whitelist"]
        self.admin = self.config["admin"]
        self.updater = Updater(self.config["token"])

        if time:
            self.time = time
            self._automatic_update()

        if handle:
            dp = self.updater.dispatcher
            dp.add_handler(CommandHandler('getid', self.get_chatid))
            dp.add_handler(CommandHandler('get_whitelist', self.get_whitelist))
            dp.add_handler(
                CommandHandler('add_whitelist',
                               self.add_whitelist,
                               pass_args=True))
            dp.add_handler(
                CommandHandler('del_whitelist',
                               self.del_whitelist,
                               pass_args=True))
            dp.add_handler(CommandHandler('get_apps', self.get_apps))
            dp.add_handler(
                CommandHandler('add_app', self.add_apps, pass_args=True))
            dp.add_handler(
                CommandHandler('del_app', self.del_apps, pass_args=True))
            dp.add_handler(CommandHandler('help', self.show_help))
            dp.add_handler(CommandHandler('update', self.manual_update))

            self.updater.start_polling()
            self.updater.idle()
        else:
            self.doit()
Exemplo n.º 4
0
def work():
    sql_execute(
        'ALTER TABLE "topic" ADD COLUMN "update_time" BIGINT NULL DEFAULT NULL ;'
    )
    sql_execute(
        'ALTER TABLE "user" ADD COLUMN "ip_registered" inet NULL DEFAULT NULL;'
    )
    sql_execute('drop table "notif";')
    sql_execute('drop table "mention";')
    sql_execute('drop table "user_notif_record";')

    db.create_tables([UserNotifLastInfo], safe=True)
    for i in UserModel.select().execute():
        try:
            UserNotifLastInfo.create(id=i.id, update_time=int(time.time()))
        except peewee.IntegrityError as e:
            print(e)
            db.rollback()
Exemplo n.º 5
0
from model import db
from model.test import Test

db.connect()
db.create_tables([Test], safe=True)
Exemplo n.º 6
0
def db_init():
    db.create_tables([User, ApiKey, Article], safe=True)
Exemplo n.º 7
0
Arquivo: models.py Projeto: fy0/Icarus
# coding:utf-8

from model import db
from model.user import User
from model.topic import Topic
from model.board import Board, BoardAdmin
from model.wiki import WikiItem, WikiArticle, WikiHistory
from model.reply import Reply
from model.follow import Follow


def first_run():
    if User.count() == 0:
        u = User.new('root', '123')
        Board.new('初学者', u, '你们啊,还是需要学习一个。')
        Board.new('问与答', u, '但是你们问来问去的问题呀,都 too young, too simple.')
        Board.new('游戏开发', u, '游戏制作的种种')
        Board.new('WEB开发', u, '当下最热门的技术种类')
        Board.new('发起项目', u, '已有创意,就差一个程序员/设计师/策划/运营了!')
        Board.new('项目展示', u, '今天我作为一个长者,给你们分享一点人生的经验')
        Board.new('水区', u, '社区的哪一个牛人我没有见过?我跟他们谈笑风生!')


db.connect()
db.create_tables([User, Topic, Board, BoardAdmin, WikiItem, WikiArticle, WikiHistory, Reply, Follow], safe=True)
first_run()
from model import db, Grade

db.connect()
db.create_tables([Grade])
Exemplo n.º 9
0
from model import db, SavedTotal

db.connect()
db.create_tables([SavedTotal])

Exemplo n.º 10
0
            return render_template('register.html', error="User exists")
        else:
            if Cache().check_password(str(request.form['password'])) == "1":
                return render_template('register.html',
                                       error="Your password is too common")
            db.execute_sql('insert into users values(NULL, "{}", "{}")'.format(
                request.form['login'], request.form['password']))
            Cache().validate((request.form['login'], request.form['password']))
            return render_template('login.html',
                                   message="Successfully registered")
    else:
        return render_template('register.html')


@app.route('/search', methods=['GET', 'POST'])
def search():
    results = []
    city = ""
    if request.method == 'POST':
        city = request.form['city']
        results = [
            r for r in Search().find(json.loads('{"city": "' + city + '"}'))
        ]
    return render_template('search.html', forecasts=results, city=city)


if __name__ == '__main__':
    db.connect()
    db.create_tables([Users, Forecasts])
    app.run(host='0.0.0.0', port=5000)
Exemplo n.º 11
0
"""
Scripts to run to set up our database
"""

from model import db, Order

# Create the database tables for our model
db.connect()
db.create_tables([Order])



Exemplo n.º 12
0
import socketio
from flask import Flask, request, jsonify, render_template, g
from model import db, MDevice

app = Flask("music-pi")
sio = socketio.Server(async_mode="threading")
app.wsgi_app = socketio.WSGIApp(sio, app.wsgi_app)

db.connect()
db.create_tables([MDevice])
connected_devices = {}


def _get_device(name, data={}):
    """
    A bit overloaded for convinience
    get device by name
    if the device never register before
    make a new entry in the database

    if there are additional attributes passed in
    assign these attributes and save it
    """
    d, created = MDevice.get_or_create(name=name)
    for k, v in data.items():
        setattr(d, k, v)
    if created or len(data) > 0:
        d.save()
    return d

Exemplo n.º 13
0
            for term in terms:
                sumGrade += term.termGPA * term.termCredit
                sumCredit += term.termCredit
            year.yearGPA = float('%.2f' % (sumGrade / sumCredit))
            year.yearCredit = sumCredit
            year.save()
        print("绩点计算完毕")


if __name__ == "__main__":

    # 连接数据库,建立数据表
    try:
        db.connect()
        db.create_tables([
            Student, ClassSchedule, Class, YearGrade, TermGrade, OneLessonGrade
        ])
    except:
        pass

    # 查找学生,若不存在则创建账号
    try:
        student = Student.get(Student.studentnumber == "xxxxxxxx")
    except Exception as e:
        student = Student(studentnumber="xxxxxxxx",
                          password="******")  # 用自己的教务系统账号密码
        student.save()

    spider = ZhengFangSpider(student,
                             baseUrl="http://202.195.144.168/jndx")  # 实例化爬虫
    spider.loginWithOutCode()
Exemplo n.º 14
0
from base import Gopay
from random import choice
from model import db, Transaction

email = input("Your gopay email address : ")
gopay = Gopay(email)

key = ""
seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"
for i in range(30):
    key += choice(seed)

token = gopay.login()

with open("config.py", "w") as f:
    to_be_written = 'TOKEN = "%s"\n' % token
    to_be_written += 'API_KEY = "%s"\n' % key

    f.write(to_be_written)

db.connect()
db.create_tables([Transaction])
db.close()
Exemplo n.º 15
0
# coding:utf-8

from model import db
from model.user import User,Board

db.connect()
db.create_tables([User, Board], safe=True)
Exemplo n.º 16
0
# coding:utf-8

from model import db
from model.user import User
import model.game

db.connect()
try:
    db.create_tables([User])
except:
    pass
Exemplo n.º 17
0
import os
from model import db, Charades
from playhouse.db_url import connect

db.connect()
db.create_tables([Charades])
Exemplo n.º 18
0
''' Initialize database, such as tables, data '''
import peewee

from model import db

from model.account import Account
from model.account_ask import AccountAsk

try:
    db.create_tables([Account, AccountAsk])
except peewee.OperationalError as event:
    print('OperationalError', event)
    pass
except peewee.ProgrammingError as event:
    # 错误:  关系 "bloglabels" 已经存在
    pass
Exemplo n.º 19
0
 def init_model():
     tables = [Show, Season, Episode]
     # db.drop_tables(tables)
     db.create_tables(tables, True)
Exemplo n.º 20
0
"""
Scripts to run to set up our database
"""
from datetime import datetime
from model import db, User, Task
from passlib.hash import pbkdf2_sha256

# Create the database tables for our model
db.connect()
db.drop_tables([User, Task])
db.create_tables([User, Task])

Task(name="Do the laundry.").save()
Task(name="Do the dishes.", performed=datetime.now()).save()
User(name="admin", password=pbkdf2_sha256.hash("password")).save()
User(name="bob", password=pbkdf2_sha256.hash("bobbob")).save()
Exemplo n.º 21
0
from model import db, Participant, Prize_Structure, Team

db.connect()

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([Participant, Prize_Structure, Team])

db.create_tables([Participant, Prize_Structure, Team])

play_in = Prize_Structure(advanced_to_round=0, money_share=0).save()
first = Prize_Structure(advanced_to_round=1, money_share=0).save()
second = Prize_Structure(advanced_to_round=2, money_share=0).save()
sweet_sixteen = Prize_Structure(advanced_to_round=3, money_share=0.03).save()
elite_eight = Prize_Structure(advanced_to_round=4, money_share=0.05).save()
final_four = Prize_Structure(advanced_to_round=5, money_share=0.1).save()
championship = Prize_Structure(advanced_to_round=6, money_share=0.16).save()
winner = Prize_Structure(advanced_to_round=7, money_share=0.2).save()

teams = [('Villanova', 'East', 1, first), ('Michigan', 'West', 3, first),
         ('Kansas', 'Midwest', 1, first), ('Loyola (IL)', 'South', 11, first),
         ('Kansas State', 'South', 9, first),
         ('Florida State', 'West', 9, first), ('Duke', 'Midwest', 2, first),
         ('Texas Tech', 'East', 3, first), ('Kentucky', 'South', 5, first),
         ('Nevada', 'South', 7, first), ('Gonzaga', 'West', 4, first),
         ('Texas A&M', 'West', 7, first), ('Clemson', 'Midwest', 5, first),
         ('Syracuse', 'Midwest', 11, play_in), ('W. Virginia', 'East', 5,
                                                first),
         ('Purdue', 'East', 2, first), ('Marshall', 'East', 13, first),
         ('UMBC', 'South', 16, first), ('Buffalo', 'South', 13, first),
         ('Tennessee', 'South', 3, first), ('Cincinnati', 'South', 2, first),
Exemplo n.º 22
0
    sql_execute('alter table "user" drop column key')
    sql_execute('alter table "user" drop column key_time')

    sql_execute('alter table "upload" add column filename text')
    sql_execute('alter table "upload" add column source text')


db.connect()
work()

db.create_tables([Test, BoardModel, Follow, CommentModel, TopicModel, UserModel,
                  WikiArticleModel,
                  NotificationModel, UserNotifLastInfo,
                  UserOAuth,
                  UserToken,
                  UploadModel,
                  ManageLogModel,
                  Mention,
                  PostStatsModel,
                  StatsLog], safe=True)

work()

sql_execute("""
ALTER TABLE "board" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "topic" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "number" SET DEFAULT nextval('user_count_seq')::bigint;
""")

WikiArticleModel.get_sidebar_article()
Exemplo n.º 23
0
from model import db, SavedDonation

db.connect()
db.create_tables([SavedDonation])
Exemplo n.º 24
0
def init_db():
    """Initializes the database."""
    db = get_db()
    db.create_tables([User, Task])
    db.save()
Exemplo n.º 25
0
# coding:utf-8

from model import db
from model.user import User
from model.todo import Todo

db.connect()
db.create_tables([User, Todo], safe=True)
Exemplo n.º 26
0
def create_tables():
    db.create_tables([Person,Consult,ConsultExt])
Exemplo n.º 27
0
import random
from model import db, Donor, Donation, User
from passlib.hash import pbkdf2_sha256

db.connect()

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([Donor, Donation, User])

db.create_tables([Donor, Donation, User])

alice = Donor(name="Alice")
alice.save()

bob = Donor(name="Bob")
bob.save()

charlie = Donor(name="Charlie")
charlie.save()

donors = [alice, bob, charlie]

for x in range(30):
    Donation(donor=random.choice(donors), value=random.randint(100,
                                                               10000)).save()

User(name='admin', password=pbkdf2_sha256.hash("password")).save()
Exemplo n.º 28
0
from model import db, Todo,Vocab,Simple
import config


# db.connect()

if(not db.get_tables()):
    db.create_tables([Todo, Vocab, Simple])

# new = Todo.create(id=2,content="selam naber",tags="Useless,")
# newV = Vocab.create(id=1,content="selam: naber", tags="Useless,")
# newC = Content.create(id=1,content="Selam naber.", tags="Useless,")

# todo Wrapper class      
class todoW:
    def select_all(): # todo select all
        # return [x for x in Todo.select()]
        return Todo.select()

    def add(content, tags):
        a = Todo.create(content=content, tags = tags) # this is an insert query 

    def update_is_done(id):
        a = Todo.update(is_done=True).where(Todo.id == id)   
        return a.execute()

    def delete_by_id(id):
        a = Todo.select().where(Todo.id==id)
        a.delete_instance()
        
    def add_tag_by_id(id, _tags):
Exemplo n.º 29
0
from model import db, Message

db.connect()
db.create_tables([Message])
Exemplo n.º 30
0
# coding:utf-8

from model import db
from model.test import Test
from model.user import User
from model.chat_log import ChatLog
from model.file_log import FileLog
from model.flag_log import FlagLog

db.connect()
db.create_tables([Test, User, ChatLog, FileLog, FlagLog], safe=True)
Exemplo n.º 31
0
    $$ LANGUAGE plpgsql;
    CREATE SEQUENCE IF NOT EXISTS id_gen_seq NO MINVALUE NO MAXVALUE START 4096 NO CYCLE; /* 0x1000 */
    CREATE SEQUENCE IF NOT EXISTS user_count_seq NO MINVALUE NO MAXVALUE START 1 NO CYCLE;
        """)

    db.execute_sql("""
    CREATE EXTENSION IF NOT EXISTS hstore;
    CREATE EXTENSION IF NOT EXISTS citext;
    """)
except peewee.ProgrammingError:
    # permission denied to create extension "hstore"
    db.rollback()

db.create_tables([
    Test, Board, Follow, Comment, Topic, User, WikiArticle, Notification,
    UserNotifLastInfo, UserOAuth, Upload, ManageLog, Mention, Statistic,
    Statistic24h
],
                 safe=True)

try:
    db.execute_sql("""
ALTER TABLE "board" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "topic" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "number" SET DEFAULT nextval('user_count_seq')::bigint;
    """)

except peewee.ProgrammingError:
    db.rollback()

WikiArticle.get_sidebar_root_article()
Exemplo n.º 32
0
import random
from peewee import DoesNotExist
from passlib.hash import pbkdf2_sha256
from model import db, Donor, Donation, Admin

db.connect()
# db.execute_sql('PRAGMA foreign_keys = ON;')

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([Donor, Donation, Admin])
#
db.create_tables([Donor, Donation, Admin])

alice = Donor.create(name="Alice")
# alice.save()

bob = Donor.create(name="Bob")
# bob.save()

charlie = Donor.create(name="Charlie")
# charlie.save()

donors = [alice, bob, charlie]

for x in range(30):
    Donation.create(donor=random.choice(donors),
                    value=random.randint(100, 10000))

user1 = Admin.create(user="******", password=pbkdf2_sha256.hash("password"))
user2 = Admin.create(user="******", password=pbkdf2_sha256.hash("123456"))
Exemplo n.º 33
0
    END;
    $$ LANGUAGE plpgsql;
    CREATE SEQUENCE IF NOT EXISTS id_gen_seq NO MINVALUE NO MAXVALUE START 4096 NO CYCLE; /* 0x1000 */
    CREATE SEQUENCE IF NOT EXISTS user_count_seq NO MINVALUE NO MAXVALUE START 1 NO CYCLE;
        """)

    db.execute_sql("""
    CREATE EXTENSION IF NOT EXISTS hstore;
    CREATE EXTENSION IF NOT EXISTS citext;
    """)
except peewee.ProgrammingError:
    # permission denied to create extension "hstore"
    db.rollback()

db.create_tables([
    Test, Board, Follow, Comment, Topic, User, WikiItem, WikiArticle,
    WikiHistory, Notification, UserNotifRecord, UserOAuth, Upload, ManageLog,
    Statistic, Statistic24h
],
                 safe=True)

try:
    db.execute_sql("""
ALTER TABLE "board" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "topic" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
    """)

except peewee.ProgrammingError:
    db.rollback()
Exemplo n.º 34
0
# coding:utf-8

from model import db
from model.test import Test
from model.user import User

db.connect()
db.create_tables([Test, User], safe=True)
Exemplo n.º 35
0
import random
from model import db, Donor, Donation, User
from passlib.hash import pbkdf2_sha256

db.connect()

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([User, Donor, Donation])

db.create_tables([User, Donor, Donation])

alice = Donor(name="Alice")
alice.save()

bob = Donor(name="Bob")
bob.save()

charlie = Donor(name="Charlie")
charlie.save()

donors = [alice, bob, charlie]

for x in range(30):
    Donation(donor=random.choice(donors), value=random.randint(100,
                                                               10000)).save()

User(name="admin", password=pbkdf2_sha256.hash("password")).save()
User(name="bob", password=pbkdf2_sha256.hash("bobbob")).save()
Exemplo n.º 36
0
# coding:utf-8

from model import db
from model.article import Article
from model.comment import Comment
from model.user import User
from model.board import Board

db.connect()
db.create_tables([User, Article, Board, Comment], safe=True)