예제 #1
0
 def test_JSONEncoder(self):
     """ Tests that objects invokes to_json """
     user = models.User(email=['*****@*****.**']).put()
     assert isinstance(user, ndb.Key)
     models.JSONEncoder().default(user)
예제 #2
0
#!venv/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db, models
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
    u = models.User(username='******', password='******', is_admin=True)
    u.set_password('admin')
    db.session.add(u)
    db.session.commit()
    m = models.Message(content="Welcome on the chat!", author=u)
    db.session.add(m)
    db.session.commit()
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))
예제 #3
0
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db, models, forms
from passlib.hash import sha256_crypt
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))
admin = models.User(username="******",
                    email="*****@*****.**",
                    hashed_password=sha256_crypt.hash("password"),
                    admin=True,
                    last_name="smith",
                    first_name="john")
db.session.add(admin)
db.session.commit()
예제 #4
0
from app import db, models

userToAdd = raw_input(
    "Please enter user to create (by user name; e.g. E201): ")

user = models.User.query.filter_by(name=userToAdd).first()
if user != None:
    print "User " + userToAdd + " already exists."
else:
    confirm = raw_input("Create user " + userToAdd + "? [Y/N] : ")
    if confirm[0] == "Y" or confirm[0] == "y":
        u = models.User(name=userToAdd)
        db.session.add(u)
        db.session.commit()
        print "User " + userToAdd + " added."
예제 #5
0
파일: data.py 프로젝트: hill/UEM2
def generate_demo_data(session: Session):
    """Generates demonstration data from models"""

    # check that the db is empty
    if session.query(models.User).first():
        log.info("Data already exists, skipping data generation.")
        return
    log.info("Generating demo data.")

    user = models.User(
        name="Tom Hill",
        email="*****@*****.**",
        password_hash=security.get_password_hash("password"),
        stripe_customer_id=stripe.Customer.create()["id"],
    )

    session.add(user)
    session.commit()
    session.refresh(user)

    discrete_maths = models.Course(
        name="Introduction to Reinforcement Learning",
        code="RL479",
        description="description",
        status="completing",
        due="2021-12-12",
        syllabus=[
            {
                "id": 1,
                "name": "Introduction to Reinforcement Learning",
                "completed": False,
            },
            {
                "id": 2,
                "name": "Exploration and Control",
                "completed": False
            },
            {
                "id": 3,
                "name": "MDPs and Dynamic Programming",
                "completed": False
            },
            {
                "id": 4,
                "name": "Fundementals of Dynamic Programming Algorithms",
                "completed": False,
            },
            {
                "id": 5,
                "name": "Model-Free Prediction",
                "completed": False
            },
            {
                "id": 6,
                "name": "Model-Free Control",
                "completed": False
            },
            {
                "id": 7,
                "name": "Function Approximation",
                "completed": False
            },
            {
                "id": 8,
                "name": "Planning & Models",
                "completed": False
            },
            {
                "id": 9,
                "name": "Policy-Gradient and Actor-Critic Methods",
                "completed": False,
            },
            {
                "id": 10,
                "name": "Approximate Dynamic Programming",
                "completed": False
            },
            {
                "id": 11,
                "name": "Multi-Step & Off Policy",
                "completed": False
            },
            {
                "id": 12,
                "name": "Deep RL 1",
                "completed": False
            },
            {
                "id": 13,
                "name": "Deep RL 2",
                "completed": False
            },
        ],
        cover={"color": "#8bbeb2"},
        user_id=user.id,
    )

    maths = models.Topic(name="mathematics")
    algebra = models.Topic(name="algebra")

    session.add_all([discrete_maths, maths, algebra])
    session.commit()
    session.refresh(maths)
    session.refresh(algebra)  # could try session.expire_all() instead?

    linear_algebra = models.Resource(
        name="Interactive Linear Algebra",
        url="http://textbooks.math.gatech.edu/ila/index.html",
        user_id=user.id,
        topics=[maths, algebra],
    )

    big_exam = models.Assignment(
        name="Big Exam",
        description="Examination of:Set theory, Proof, Graph Theory",
        due="2021-12-12",
        course_id=discrete_maths.id,
        status="in_progress",
        weight=50,
    )

    session.add_all([linear_algebra, big_exam])
    session.commit()
예제 #6
0
from app import db, models
u1 = models.User(name='john', email='*****@*****.**')
db.session.add(u1)
db.session.commit()
u2 = models.User(name='susan', email='*****@*****.**')
db.session.add(u2)
db.session.commit()
print("finished adding data")
예제 #7
0
def test_models(client):
    from app import models
    u = models.User("test", "*****@*****.**", "test", True)
예제 #8
0
def db_add_user(db: Session, user: schemas.UserCreate):
    db_user = models.User(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
예제 #9
0
    {
        "nickname": "alex",
        "email": "alex@email"
    },
    {
        "nickname": "Toms",
        "email": "Toms@email"
    },
    {
        "nickname": "stevn",
        "email": "stevn@email"
    },
]

for user in insert_users:
    u = models.User(nickname=user["nickname"], email=user["email"])
    db.session.add(u)

users = models.User.query.all()
print(users)

for user in users:
    print(user.id, user.nickname)

u = models.User.query.get(1)
p = models.Post(body="my first post!",
                timestamp=datetime.datetime.utcnow(),
                author=u)
db.session.add(p)

# users = models.User.query.all()
예제 #10
0
 def test_can_index(self):
     """Tests that index only works for user"""
     user = models.User(email=['*****@*****.**']).put().get()
     need = Need('index')
     self.assertTrue(
         user._can(user, need, None, MagicMock(filter=lambda *args: True)))
예제 #11
0
 def test_pre_put_hook(self):
     """Tests that pre put hook for user works"""
     with self.assertRaises(BadValueError):
         models.User().put()
예제 #12
0
 def test_can_get_not_user(self):
     """Tests can get with invalid user"""
     user = models.User(email=['*****@*****.**']).put().get()
     need = Need('get')
     self.assertFalse(user._can(user, need, None, None))
예제 #13
0
 def test_can_lookup(self):
     """Tests that anyone can lookup"""
     user = models.User(email=['*****@*****.**']).put().get()
     need = Need('lookup')
     self.assertTrue(user._can(user, need, None, None))
예제 #14
0
 def test_comment_can(self):
     """test commentp ermissions"""
     admin = models.User(email=['*****@*****.**'], is_admin=True).put().get()
     self.assertTrue(models.Comment._can(admin, None))
     weird = Need('weird')
     self.assertFalse(models.Comment._can(MagicMock(is_admin=False), weird))
예제 #15
0
import datetime
from app import db, models
db.create_all()

u = models.User(username='******', email='*****@*****.**')
db.session.add(u)
p = models.Post(body='doodoo', timestamp=datetime.datetime.utcnow(), author=u)
db.session.add(p)
db.session.commit()
예제 #16
0
def create_file(db: Session = Depends(deps.get_db),
                updateSupport: bool = False,
                file: UploadFile = File(...)):
    def check_dict_label(label, code):
        dict = db.query(models.Dict_Data).outerjoin(
            models.Dict_Type,
            models.Dict_Type.id == models.Dict_Data.type_id).filter(
                models.Dict_Data.label == label,
                models.Dict_Type.code == code).one()
        return dict

    try:
        io = BytesIO(file.file.read())
        wb = load_workbook(io, read_only=True)
        ws = wb.active  # wb.worksheets[0]
        for row in ws.iter_rows(min_row=2):
            # dict_data
            sex = check_dict_label(row[5].value.strip(""), "sex").label
            status = check_dict_label(row[6].value.strip(""),
                                      "user_status").label

            user = {
                "username": row[0].value.strip(""),
                "nickname": row[1].value.strip(""),
                "identity_card": row[3].value.strip(""),
                "phone": row[4].value.strip(""),
                "sex": sex,
                "status": status,
                "hashed_password": get_password_hash(settings.INIT_PASSWORD)
            }
            department = db.query(models.Department).filter(
                models.Department.name == row[2].value.strip("")).one()
            posts = db.query(models.Dict_Data).outerjoin(
                models.Dict_Type,
                models.Dict_Type.id == models.Dict_Data.type_id).filter(
                    models.Dict_Data.label.in_(
                        row[7].value.strip("").split(",")),
                    models.Dict_Type.code == "post").all()
            exist_user = db.query(
                models.User).filter(models.User.username == user["username"])

            if not exist_user.first():
                user = models.User(**user)
                db.add(user)
                db.flush()
                user_department = {
                    "user_id": user.id,
                    "department_id": department.id
                }
                db.add(models.User_Department(**user_department))
                user_dict = [{
                    "user_id": user.id,
                    "dict_id": post.id
                } for post in posts]
                db.bulk_insert_mappings(models.User_Dict, user_dict)
            elif updateSupport:
                exist_user_id = exist_user.one().id
                exist_user.update(user)
                db.flush()
                # department
                db.query(models.User_Department).filter(
                    models.User_Department.user_id == exist_user_id).delete()
                user_department = {
                    "user_id": exist_user_id,
                    "department_id": department.id
                }
                db.add(models.User_Department(**user_department))
                # post
                db.query(models.User_Dict).filter(
                    models.User_Dict.user_id == exist_user_id).delete()
                user_dict = [{
                    "user_id": exist_user_id,
                    "dict_id": post.id
                } for post in posts]
                db.bulk_insert_mappings(models.User_Dict, user_dict)
        return {"code": 20000, "message": "导入成功"}
    except Exception as exc:
        raise HTTPException(status_code=200,
                            detail=f"导入失败,请检查数据!   Error Reason: {exc}")
    finally:
        wb.close()
import csv
from app import app, create_app, db
from app import models

hr = models.Department(name='HR')
sales = models.Department(name='Sales')
legal = models.Department(name='Legal')
engineering = models.Department(name='Engineering')
db.add(hr)
db.add(sales)
db.add(legal)
db.add(engineering)

admin = models.User(username="******", email="*****@*****.**")
guest = models.User(username="******", email="*****@*****.**")
jan = models.User(username="******", email="*****@*****.**")
hein = models.User(username="******", email="*****@*****.**")
klaas = models.User(username="******", email="*****@*****.**")
pit = models.User(username="******", email="*****@*****.**")

db.add(admin)
db.add(guest)
db.add(jan)
db.add(hein)
db.add(klaas)
db.add(pit)

hr.users.append(admin)
sales.users.append(jan)
legal.users.append(hein)
engineering.users.append(klaas)
예제 #18
0
from app import db, models
from datetime import datetime

date = datetime.strptime('2018-03-01', '%Y-%m-%d')
birth_date = datetime.strptime('1997-01-24', '%Y-%m-%d')

db.session.add(models.Club(club_name='Pebblebrook High School'))

db.session.add(
    models.User(username='******',
                password='******',
                first_name='Sruti',
                last_name='Guhathakurta',
                email='*****@*****.**',
                profile_picture='srutig.jpg',
                type='member',
                gender='Female',
                race='asian-indian',
                address_street='351 Sinclair Ave NE',
                address_city='Atlanta',
                address_state='GA',
                address_zip='30307',
                birth_date=birth_date))
db.session.add(
    models.Member(username='******',
                  join_date=date,
                  club_name='Pebblebrook High School',
                  commitment_pledge=date,
                  photo_release=date,
                  education='some-college',
                  marital_status='single',
                  income='10000'))
예제 #19
0
def main():
    db.drop_all()
    db.create_all()

    u1 = models.User(username='******',
                     password='******',
                     admin=True,
                     active=True)
    u2 = models.User(username='******',
                     password='******',
                     admin=False,
                     active=True)
    u3 = models.User(username='******',
                     password='******',
                     admin=False,
                     active=True)
    u4 = models.User(username='******',
                     password='******',
                     admin=False,
                     active=False)
    db.session.add_all([u1, u2, u3, u4])
    db.session.commit()

    t1 = services.create_task(created_by=u1,
                              assigned_to=u2,
                              origin='ba',
                              destination='nr',
                              status=models.TaskStatus.NEW,
                              comments='short comment')
    t2 = services.create_task(created_by=u2,
                              assigned_to=u3,
                              origin='nr',
                              destination='bb',
                              status=models.TaskStatus.PROCESSING,
                              comments='')
    t3 = services.create_task(created_by=u3,
                              assigned_to=u1,
                              origin='ke',
                              destination='po',
                              status=models.TaskStatus.FINISHED,
                              comments='short comment')
    t4 = services.create_task(created_by=u1,
                              assigned_to=u2,
                              origin='ba',
                              destination='nr',
                              status=models.TaskStatus.NEW,
                              comments='')
    t5 = services.create_task(created_by=u2,
                              assigned_to=u3,
                              origin='nr',
                              destination='bb',
                              status=models.TaskStatus.PROCESSING,
                              comments='short comment')
    t6 = services.create_task(created_by=u3,
                              assigned_to=u1,
                              origin='ke',
                              destination='po',
                              status=models.TaskStatus.FINISHED,
                              comments='')

    services.update_task_set_processing(u1, t1.id)
    services.update_task_set_finished(u1, t1.id)
    services.update_task_set_archived(u1, t1.id)

    for t in services.find_all_tasks():
        print(t)
예제 #20
0
def addUser(nickname, password):
    if not checkNickname(nickname):
        password = get_hash_password(password, app.config['SECRET_KEY'])
        u = models.User(nickname=nickname, password=password)
        db.session.add(u)
        db.session.commit()
예제 #21
0
#!flask/bin/python
from app import db, models

db.create_all()

user_tom = models.User(username='******', password='******')
user_jim = models.User(username='******', password='******')

db.session.add(user_tom)
db.session.add(user_jim)
db.session.commit()
예제 #22
0
파일: run.py 프로젝트: kurohai/flask-task
"""Run the server in either production or development."""
from app import app, db, models
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from passlib.hash import sha256_crypt

if app.config['ENV'] == 'PROD':
    db.create_all()
    email = app.config['ADMIN_EMAIL'].lower()
    pw = app.config['ADMIN_PW']
    hash = sha256_crypt.encrypt(pw)
    user = models.User(email, hash)
    db.session.add(user)
    db.session.commit()
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(9000)
    print("Running production on 9000")
    IOLoop.instance().start()
elif app.config['ENV'] == 'DEV':
    db.drop_all()
    db.create_all()
    email = app.config['ADMIN_EMAIL']
    pw = app.config['ADMIN_PW']
    hash = sha256_crypt.encrypt(pw)
    user = models.User(email, hash)
    db.session.add(user)
    db.session.commit()
    print("Running development")
    app.run(debug=True)
예제 #23
0
# Clear existing users/metrics/records
users = models.User.query.all()
for u in users:
    db.session.delete(u)

metrics = models.Metric.query.all()
for m in metrics:
    db.session.delete(m)

records = models.Record.query.all()
for r in records:
    db.session.delete(r)

# Create Users
user1 = models.User(email='*****@*****.**', password='******')
user2 = models.User(email='*****@*****.**', password='******')

# Add users to session and commit
db.session.add_all([user1, user2])
db.session.commit()

# Assign user ids to variables
user1_id = db.session.query(models.User.id).filter_by(email='*****@*****.**')
user2_id = db.session.query(models.User.id).filter_by(email='*****@*****.**')

# Create metrics
metric1 = models.Metric(user_id=user1_id,
                        name='Swimming',
                        is_bool=True,
                        max_val=1,
예제 #24
0
from app import app, models


users = [
    {
        'email': '*****@*****.**',
        'first_name': 'Toto',
        'last_name': 'Titi',
        'phone': '+331',
        'is_forwarder': False,
        'password': '******'
    },
    {
        'email': '*****@*****.**',
        'first_name': 'Tata',
        'last_name': 'Tutu',
        'phone': '+332',
        'is_forwarder': True,
        'password': '******'
    }
]


with app.app_context():
    for user in users:
        obj = models.User(**user)
        try:
            obj.add()
        except Exception as e:
            print('Error:', e)
예제 #25
0
def _insert_user(session, username):
    user = models.User(username=username)

    session.add(user)
    session.commit()
예제 #26
0
파일: manage.py 프로젝트: Alge/flask-base
def seed():
    "Load some initial data into the DB. Only use during dev..."
    user = models.User("*****@*****.**", "admin", "password")
    user.id_admin = True
    user.save()
예제 #27
0
import os.path
from datetime import datetime

db.create_all()

if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))

print("database created")

#################################################################################
user1 = models.User('1', '1')
user2 = models.User('bhh', 'bhh')

patient1 = models.Patient(u'BHH', u'098', u'32', u'nam', u'ở chùa',
                          u'đẹp trai', u'đẹp trai')
patient2 = models.Patient(u'TheMoon', u'0923', u'23', u'nữ', u'vô gia cư',
                          u'đẹp gái', u'đẹp gái')
patient3 = models.Patient(u'TheSun', u'0923', u'23', u'pêđê', u'trên sao hỏa',
                          u'đẹp pêde', u'đẹp pêde')

medicine1 = models.Medicine(u'aspirin', u'mã 1', u'nhóm 1', u'hoạt tính 1',
                            u'hộp', 10, 10000)
medicine2 = models.Medicine(u'toplexin', u'mã 2', u'nhóm 12', u'hoạt tính 2',
                            u'vỉ', 130, 25400)
medicine3 = models.Medicine(u'pracetamon', u'mã 2', u'nhóm 12', u'hoạt tính 2',
                            u'vỉ', 130, 25400)
예제 #28
0
def index():
    date_seven_days_ago = (datetime.datetime.now() -
                           datetime.timedelta(days=7)).date()
    current_form = CurrentDataForm()
    crop_form = CropSelectorForm()
    if current_form.validate_on_submit():
        print "processing!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        if (valid_email(current_form.email.data)
                and is_json(current_form.fieldpoly.data)):
            if (valid_field(current_form.fieldpoly.data)):

                if (models.User.query.filter(models.User.email == current_form.
                                             email.data).first() == None):
                    u = models.User(timestamp=datetime.datetime.utcnow(),
                                    email=current_form.email.data)
                    db.session.add(u)
                else:
                    u = models.User.query.filter(
                        models.User.email == current_form.email.data).first()
                rq = models.Request(
                    body=current_form.fieldpoly.data,
                    timestamp=datetime.datetime.utcnow(),
                    crop_type='None',
                    season='Now!',
                    processed=False,
                    author=u,
                    request_queued=False)  #crop_type="Winterwheat"
                db.session.add(rq)
                db.session.commit()

                flash('Data is going to be send to: %s' % crop_form.email.data)
                #flash('GOT="%s", email=%s' % (form.fieldpoly.data, crop_form.email.data))
            else:
                flash(
                    "Not a valid JSON polygon!!! Either the area is to large/small or you have multiple areas"
                )
        else:
            if (is_json(crop_form.fieldpoly.data)):
                flash('Not a valid email:%s' % crop_form.email.data)
            else:
                flash('BROKEN JSON SYNTAX! Did you copy it correctly')
        return redirect('/')

    if crop_form.validate_on_submit():
        #flash("validate_on_submit()")
        if (valid_email(crop_form.email.data)
                and is_json(crop_form.fieldpoly.data)):
            if (valid_field(crop_form.fieldpoly.data)):

                if (models.User.query.filter(models.User.email == crop_form.
                                             email.data).first() == None):
                    u = models.User(timestamp=datetime.datetime.utcnow(),
                                    email=crop_form.email.data)
                    db.session.add(u)
                else:
                    u = models.User.query.filter(
                        models.User.email == crop_form.email.data).first()
                rq = models.Request(
                    body=crop_form.fieldpoly.data,
                    timestamp=datetime.datetime.utcnow(),
                    crop_type=crop_form.crop_type.data,
                    season=crop_crop_form.season.data,
                    processed=False,
                    author=u,
                    request_queued=False)  #crop_type="Winterwheat"
                db.session.add(rq)
                db.session.commit()

                flash('Data is going to be send to: %s' % crop_form.email.data)
                #flash('GOT="%s", email=%s' % (form.fieldpoly.data, crop_form.email.data))
            else:
                flash(
                    "Not a valid JSON polygon!!! Either the area is to large/small or you have multiple areas"
                )
        else:
            if (is_json(crop_form.fieldpoly.data)):
                flash('Not a valid email:%s' % crop_form.email.data)
            else:
                flash('BROKEN JSON SYNTAX! Did you copy it correctly')
        return redirect('/')

    return render_template(
        'login.html',
        title='Fieldbabel service for sentinel data',
        current_form=current_form,
        crop_form=crop_form,
        requests=models.Request.query.filter(
            models.Request.processed == False).order_by(
                models.Request.id).all(),
        peformed=models.Request.query.filter(
            models.Request.processed == True,
            models.Request.timestamp >= date_seven_days_ago).order_by(
                models.Request.id).all(),
        html=HTMLParser())
예제 #29
0
from app import db, models
import datetime

u = models.User(nickname='john', email='*****@*****.**')
db.session.add(u)
db.session.commit()
u = models.User.query.get(1)
p = models.Post(body='my first post!',
                timestamp=datetime.datetime.utcnow(),
                author=u)
db.session.add(p)
db.session.commit()
예제 #30
0
 def test_course_get_students_basic(self):
     """Tests that get_students functions"""
     student_key = models.User(email=['*****@*****.**']).put()
     course = make_fake_course(student_key.get())
     students = course.get_students(student_key)
     self.assertTrue(isinstance(students, list))