예제 #1
0
파일: register.py 프로젝트: Bankde/icmm-r4t
def main():
    debug_flag = ENV_MODE != 'production'
    
    try:
        app.run(host=BIND_ADDRESS, port=PORT, debug=debug_flag)
    finally:
        # Caught an interrupt or some error.
        UserDB.close()
예제 #2
0
def prep_db():
    user_db = UserDB()
    try:
        user_db.init_conn()
    except Exception as e:
        print(e)
        user_db.release_conn()
        user_db = None
    return user_db
예제 #3
0
    def on_get(self, req, res):
        user = UserDB()
        users = user.list_user()

        LOG.info(("Users fectched: {0}.").format(
            json.dumps(users).decode("unicode-escape")))

        res.status = httplib.OK
        res.body = json.dumps(users)
예제 #4
0
def get_new_model(user_username):
    if request.method == 'POST':
        try:
            newform = request.json
            model = newform['model']
            UserDB.add_model(user_username, model)
            return jsonify({'message': 'model created'})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'bad request method'})
예제 #5
0
def get_db():
    """Function for get db inside Flask app.
    Must call this funtions inside app context and do not connect database before app run.
    Example:
        with app.app_context():
            db = get_db()
    """
    if 'db' not in g:
        UserDB.connect(config["db"]["path"])
        g.db = UserDB
    return g.db
예제 #6
0
파일: register.py 프로젝트: Bankde/icmm-r4t
def get_db():
    """Function for get db inside Flask app.
    Must call this funtions inside app context and do not connect database before app run.
    Example:
        with app.app_context():
            db = get_db()
    """
    db = getattr(g, "_database", None)
    if db is None:
        UserDB.connect(SQLITE_DB_PATH)
        db = UserDB
    return db
예제 #7
0
    def on_put(self, req, res, userId):
        data = req.stream.read()
        data = json.loads(data)

        sche = schema.Schema("password")
        sche.validate(data)

        user = UserDB()
        user.change_password(userId, data['password'])

        res.status = httplib.OK
        res.body = "Password for user %s is changed successfully" % userId
예제 #8
0
def main(args):
    # Read source
    if args.source_type == "excel":
        df = pd.read_excel(open(args.source, 'rb'),
                           sheet_name=args.sheet_name,
                           encoding='utf-8')
    else:
        df = pd.read_csv(args.source)

    UserDB.connect(args.db_path)
    UserDB.initSchema()
    # Iterate data
    users = []
    for row in df.values:
        bibNumber = row[0]
        firstName = row[3]
        lastName = row[4]
        bibName = row[6]
        telNumber = row[7]
        raceCategory = row[9]
        challenge = row[10]
        try:
            UserDB.insertUser(firstName, lastName, bibName, challenge,
                              raceCategory, telNumber, bibNumber)
        except Exception as e:
            print("Error %s: %s" % (str(e), bibNumber))
    UserDB.close()
예제 #9
0
def main(args):
    # Read source
    if args.source_type == "excel":
        df = pd.read_excel(open(args.source,'rb'), sheet_name=args.sheet_name, encoding='utf-8')
    else:
        df = pd.read_csv(args.source)

    UserDB.connect(args.db_path)
    UserDB.initSchema()
    # Iterate data
    users = []
    for row in df.values:
        firstname = row[3]
        lastname = row[4]
        teamName = None
        distance = row[8]
        if "10 KM" not in distance:
            # Skip 5K runner
            continue

        first10k_word = row[10]
        if first10k_word == "เคย":
            first10k = 0
        elif first10k_word == "ไม่เคย":
            first10k = 1
        else:
            assert(0)
            
        user = (firstname, lastname, teamName, first10k)
        users.append(user)
    print("Inserting %d users" % (len(users)))
    UserDB.insertUsers(users)
    UserDB.close()
예제 #10
0
def main():
    global config
    config = load_json_config(DEFAULT_CONFIG_PATH)
    server_conf = config["server"]

    debug_flag = False
    if "debug" in config["server"]:
        debug_flag = config["server"]["debug"]

    try:
        app.run(host=server_conf["bindAddress"],
                port=server_conf["port"],
                debug=debug_flag)
    finally:
        # Caught an interrupt or some error.
        UserDB.close()
예제 #11
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testSuccess_AllFirst10k(users):
    data = UserDB.checkTeam("HelloWorld", users["1"], users["2"], users["5"],
                            users["8"])
    assert (data["success"] == True)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.OK)
예제 #12
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testSuccess_SwapPosition_2(users):
    data = UserDB.checkTeam("HelloWorld", users["1"], users["3"], users["4"],
                            users["2"])
    assert (data["success"] == True)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.OK)
예제 #13
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testFail_AllNotFirst10k(users):
    data = UserDB.checkTeam("HelloWorld", users["3"], users["4"], users["6"],
                            users["9"])
    assert (data["success"] == False)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.NOT_FIRST_10K)
    assert (data["member2"] == ResMessage.NOT_FIRST_10K)
    assert (data["member3"] == ResMessage.NOT_FIRST_10K)
    assert (data["member4"] == ResMessage.NOT_FIRST_10K)
예제 #14
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testSuccess_TwoFirst10k(users):
    data = UserDB.checkTeam("MyNewTeam", users["1"], users["2"], users["3"],
                            users["4"])
    assert (data["success"] == True)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.OK)
예제 #15
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testFail_AlreadyRegisteredAndThree10k(users):
    data = UserDB.checkTeam("HelloWorld", users["3"], users["4"], users["6"],
                            users["7"])
    assert (data["success"] == False)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.USER_REGISTERED)
예제 #16
0
def get_all_models(user_username):
    if request.method == 'GET':
        try:
            models = UserDB.get_all_models(user_username)
            return jsonify({'message': models})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'wrong method'})
예제 #17
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testFail_DupTeam(users):
    data = UserDB.checkTeam("MyTeam", users["1"], users["2"], users["3"],
                            users["4"])
    assert (data["success"] == False)
    assert (data["teamName"] == ResMessage.DUP_TEAM_NAME)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.OK)
예제 #18
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testFail_DupUserAllFirst10k(users):
    data = UserDB.checkTeam("HelloWorld", users["1"], users["2"], users["5"],
                            users["5"])
    print(data)
    assert (data["success"] == False)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.OK)
    assert (data["member4"] == ResMessage.DUP_USER)
예제 #19
0
파일: test_db.py 프로젝트: Bankde/icmm-r4t
def testFail_UserNotExist(users):
    notExistUser = {"firstname": "Z", "lastname": "Z"}
    data = UserDB.checkTeam("HelloWorld", users["1"], users["2"], notExistUser,
                            users["4"])
    assert (data["success"] == False)
    assert (data["teamName"] == ResMessage.OK)
    assert (data["member1"] == ResMessage.OK)
    assert (data["member2"] == ResMessage.OK)
    assert (data["member3"] == ResMessage.USER_NOT_FOUND)
    assert (data["member4"] == ResMessage.OK)
예제 #20
0
    def on_post(self, req, res):
        data = req.stream.read()
        data = json.loads(data)

        sche = schema.Schema("user")
        sche.validate(data)

        desc = "Normal user"
        if 'description' in data:
            desc = data['description']

        role = 0
        if 'role' in data:
            role = data['role']

        user = UserDB()
        user.add_user(data['id'], data['name'], data['password'], role, desc)

        res.status = httplib.OK
        res.body = "User %s is created successfully" % data['name']
예제 #21
0
def reward_user_with_tokens(user_username, nb_tokens):
    if request.method == 'POST':
        newform = request.json
        description = newform.get('desc')
        try:
            tokens_given = UserDB.reward_with_token(user_username, nb_tokens,
                                                    description)
            return jsonify({'message': tokens_given})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'bad request method'})
예제 #22
0
def assign_vehicule_to_user(user_username, vehicule_name):
    if request.method == 'GET':
        try:
            assignement = UserDB.assign_vehicule_to_user(
                user_username, vehicule_name)
            if assignement == 'checked':
                return jsonify({'message': 'vehicule assigned successfully'})
            else:
                return jsonify({'error': assignement})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'Bad Request Method'})
예제 #23
0
def login():
    if request.method == 'POST':
        try:
            form = request.json
            if UserDB.checkUser(form['username'], form['password']):
                session['user'] = form['username']
                return jsonify({'message': 'logged in'})
            else:
                return jsonify({'message': 'Wrong Informations'})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'Bad Request Method'})
예제 #24
0
def get_model_fron_vehicule():
    if request.method == 'POST':
        try:
            newform = request.json
            model = newform['model']
            user_username = newform['username']
            if UserDB.add_model_from_vehicule(model, user_username):
                user = UserDB.getOneUser(user_username)
                url = 'http:eliotctl.fr/api/add/model'
                payload = jsonify({
                    'username': user_username,
                    'public_key': user['public_key'],
                    'model': model,
                    'token': 'ULTIMATE_TOKEN'
                })
                response = requests.request("POST", url, data=payload).text
                return jsonify({'message': response})
            else:
                return jsonify({'message': 'couldnt add the model'})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'Bad Request Method'})
예제 #25
0
def create_contest(user_username):
    if request.method == 'POST':
        try:
            newform = request.json
            infos = {
                'name': newform['name'],
                'ends_days': newform['ends_days'],
                'ends_hours': newform['ends_hours']
            }
            contestCreation = UserDB.create_contest(user_username, infos)
            return jsonify({'message': contestCreation})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'Bad Request Method'})
예제 #26
0
def login():
    name = request.args.get('name')
    if not name:
        return 'name is required', 400

    password = request.args.get('password')
    if not password:
        return 'password is required', 400

    # 从数据库获取用户数据
    user = UserDB.get_user(name)
    if user.get('password') == password:
        return 'OK', 200
    else:
        return 'password is wrong', 400
예제 #27
0
def register():
    if request.method == 'POST':
        formulaire = request.json
        try:
            user = dict({
                'username': formulaire['username'],
                'password': formulaire['password'],
                'email': formulaire['email']
            })
            if UserDB.saveNewUser(user) == True:
                return jsonify({'message': 'User Registered'})
            else:
                return jsonify({'message': 'User already exists'})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'Bad Request Method'})
예제 #28
0
def request_eliot_for_tokens(user_username):

    if request.method == 'POST':
        try:
            user = UserDB.getOneUser(user_username)
            url = 'http:eliotctl.fr/interact_blockchain/ask/money'
            payload = jsonify({
                'username': user_username,
                'public_key': user['public_key'],
                'token': 'ULTIMATE_TOKEN'
            })
            response = requests.request("POST", url, data=payload).text
            return jsonify({'message': response})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'wrong method'})
예제 #29
0
def testDB(users, teams, request):
    if os.path.exists(DEFAULT_TEST_DB):
        print("Clean old test database.")
        os.remove(DEFAULT_TEST_DB)
    UserDB.connect(DEFAULT_TEST_DB)
    UserDB.initSchema()

    for team in teams.values():
        UserDB.insertTeam(team["teamName"])

    user_values = []
    for user in users.values():
        user_values.append([user["firstname"], user["lastname"], user["teamId"], user["first10k"]])
    UserDB.insertUsers(user_values)

    def testDB_teardown():
        # Teardown is called when a method using testDB ends.
        UserDB.close()
    request.addfinalizer(testDB_teardown)
예제 #30
0
def get_won_money():

    if request.method == 'GET':
        try:
            users = json.loads(
                json.dumps(list(UserDB.get_won_money()),
                           default=json_util.default))
            n = 0
            for user in users:
                total = 0
                if "tokens" in user:
                    for i in user['tokens']:
                        total += int(i[0])
                users[n]['total'] = total
                del users[n]['password']
                n += 1
            return json.dumps({'message': users})
        except Exception as e:
            return jsonify({'message': str(e)})
    else:
        return jsonify({'message': 'wrong method'})
예제 #31
0
# t.me/ClassTextBot
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging, yaml, telegram
from find_classes import Scraper
from db import UserDB

dbase = UserDB()

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)


def start(update, context):
    reply_markup = telegram.ReplyKeyboardMarkup(
        [[telegram.KeyboardButton('Share contact', request_contact=True)]])
    context.bot.sendMessage(
        chat_id=update.message.chat_id,
        text='Please share your contact so I can verify you with my database: ',
        reply_markup=reply_markup)


def contact(update, context):
    phone_number = update.message.contact.phone_number
    user_id = update.message.contact.user_id
    dbase.add_user_id(phone_number, user_id)
    context.bot.sendMessage(
        chat_id=update.message.chat_id,
        text=
        'Thanks, you\'re verified! Now type /begin to start getting class updates.'
    )