コード例 #1
0
 def generate_new_objects(self):
     for i in range(2):
         transp = Transport()
         transp.save(first_save=True)
         driver = Driver()
         driver.save(first_save=True)
         generate_object_item_delivery()
コード例 #2
0
def register_driver():
    try:
        request_json = request.get_json()
    except Exception as e:
        return make_response(
            jsonify({'return_message': 'JSON Object not found'}), 400)
    # If to validate by test_register_driver_json_not_exist, need to be improved
    if request.get_json() is None:
        return make_response(
            jsonify({'return_message': 'JSON Object not found'}), 400)

    json__ = request.get_json()
    errors = driver_schema.validate(request.get_json())
    if errors:
        return make_response(
            jsonify({
                'return_message':
                'There is some erros in your request see errors_field',
                'errors_field': errors
            }), 400)

    request_json = request.get_json()
    driver = Driver(request_json.get('name', None),
                    request_json.get('last_name', None),
                    request_json.get('date_of_birth', None),
                    request_json.get('gender_id', None),
                    request_json.get('cnh_type_id', None),
                    request_json.get('own_vehicle', None))

    driver = driver_dao.save_driver(driver)
    return jsonify({
        'driver': driver.to_json(),
        'return_message': 'Driver Registered'
    }), 201
コード例 #3
0
ファイル: views.py プロジェクト: corner-story/Transport
def register():
    json = request.get_json()
    username = json.get("username")
    phone = json.get("phone")
    password = json.get("password")
    role = json.get("role")

    data = {"state": "success", "msg": "注册成功", "data": {}}

    # 先检测该phone是否已经注册
    user = Driver.query.filter_by(phone_number=phone).first()
    if user is None:
        user = Consigner.query.filter_by(phone_number=phone).first()
    if user is not None:
        data["state"] = "error"
        data["msg"] = "该手机号码已经被注册了哦!"
        return jsonify(data)

    # 注册该用户
    if role == "1":
        user = Driver(username=username, phone_number=phone, password=password)
    else:
        user = Consigner(username=username,
                         phone_number=phone,
                         password=password)

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        data["state"] = "error"
        data["msg"] = str(e)

    return jsonify(data)
コード例 #4
0
def drivername(drivername):
    db = get_db()
    sql = "SELECT * FROM drivers WHERE name=:name"
    result = db.cursor().execute(sql, {"name": drivername}).fetchone()
    thisDriver = Driver(result[0], result[1])

    return render_template('DriverDesc.html', driver=thisDriver)
コード例 #5
0
def register_driver():
    '''Register Driver Method
    :param name(required): the name of the driver.
    :type name: string
    :param email(required): the email of the driver
    :type email: string
    :param phone_number(required): the phone number of the driver (10)
    :type phone_number: number
    :param license_number(required): the license number of the driver
    :type license_number: string
    :param car_number(required): the car number used by the driver
    :type car_number: string
    :returns: driver details
    :rtype: dictionary
    '''

    data = request.get_json()
    try:
        name = data['name']
        email = data['email']
        phone_number = data['phone_number']
        if len(str(phone_number)) != 10:
            raise BadRequest('Phone Number should be 10')
        license_number = data['license_number']
        car_number = data['car_number']
        driver = Driver(name, email, phone_number, license_number, car_number)
        db.session.add(driver)
        db.session.commit()
        res = Driver.query.get(driver.id)
        result = res.serialize()
        return jsonify(result), 201
    except (BadRequest, KeyError, exc.IntegrityError) as e:
        return make_error('failure', 400, str(e))
コード例 #6
0
    def driver_create():
        """
        Creates a record based on params supplied
        Endpoint URL: /driver/create
        :return: JSON successful message or exception response
        """
        if request.method == "POST":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Find and validate required parameters in order to create driver record
                first_name = helpers.check_missing('list', request_data,
                                                   'first_name')
                first_name = helpers.validate_string(first_name, 'first_name')

                # Middle name is optional for creating a driver
                middle_name = None
                if "middle_name" in request_data.keys():
                    middle_name = helpers.validate_string(
                        request_data['middle_name'], 'middle_name')
                last_name = helpers.check_missing('list', request_data,
                                                  'last_name')
                last_name = helpers.validate_string(last_name, 'last_name')
                dob = helpers.check_missing('list', request_data, 'dob')
                dob = helpers.validate_dob(
                    dob)  # Only accepting drivers that are 18 or older

                # Create object and save it in the database
                driver = Driver(first_name, middle_name, last_name, dob)
                driver.save()
                return jsonify({
                    "status_code": 201,
                    "message": "Driver created"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
コード例 #7
0
def insert_details(username, license, gender, dob, contact):
    print('inserting')
    new_driver = Driver(username=username,
                        license=license,
                        gender=gender,
                        dob=dob,
                        contact=contact)
    db.session.add(new_driver)
    db.session.commit()
    print('inserted')
コード例 #8
0
def sql_driver_to_obj(sql_obj):
    driver = Driver(
        sql_obj.get('Name', None),
        sql_obj.get('LastName', None),
        sql_obj.get('DateOfBirth', None),
        sql_obj.get('FK_Gender', None),
        sql_obj.get('FK_CNHTypes', None),
        sql_obj.get('OwnVehicle', None),
        sql_obj.get('ID', None))
    return driver
コード例 #9
0
    def driver_update():
        """
        Updates a record based on id supplied
        Endpoint URL: /driver/update
        :return: JSON successful message or exception response
        """
        if request.method == "PUT":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Validate id parameter passed
                id = helpers.check_missing('list', request_data, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to update
                params = {"id": id}
                driver = Driver.get(params)

                # Return 404 if not found the object to update
                if not driver:
                    return jsonify({
                        "status_code": 404,
                        "message": "Driver not found"
                    })

                # Find and validate any allowed parameters
                if "first_name" in request_data.keys():
                    driver.first_name = helpers.validate_string(
                        request_data['first_name'], 'first_name')
                if "middle_name" in request_data.keys():
                    driver.middle_name = helpers.validate_string(
                        request_data['middle_name'], 'middle_name')
                if "last_name" in request_data.keys():
                    driver.last_name = helpers.validate_string(
                        request_data['last_name'], 'last_name')
                if "dob" in request_data.keys():
                    driver.dob = helpers.validate_dob(request_data["dob"])

                # Save an object and return successful message
                driver.save()
                return jsonify({
                    "status_code": 200,
                    "message": "Driver record was updated"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
コード例 #10
0
ファイル: helper.py プロジェクト: rakshithrddy/booking
def create_maps(languages):
    from app.models import Driver
    driver_names = Driver.get_driver_names()
    drivers_details = Driver.jsonify_drivers()
    driver_to_cost_map = {}
    language_to_driver_map = {}
    if len(driver_names) == 0 or len(drivers_details) == 0:
        raise Exception("Drivers details are currently not available")
    for driver in driver_names:
        if driver is not None:
            driver_to_cost_map[driver] = drivers_details[driver]['cost_per_km']
    for language in languages:
        dr = []
        for driver in driver_names:
            if driver is not None:
                if language in drivers_details[driver]['languages']:
                    if language is not None:
                        dr.append(driver)
        language_to_driver_map[language] = dr
    return driver_to_cost_map, language_to_driver_map
コード例 #11
0
def create_driver():
    driver = Driver()
    data = request.get_json() or {}
    if 'name' not in data:
        return 'Name key not found', status.HTTP_400_BAD_REQUEST
    driver.from_dict(data, method='POST')
    driver.add_driver(driver)
    response = jsonify(driver.to_dict())
    response.status_code = 201
    return response
コード例 #12
0
    def driver_get():
        """
        Gets a record based on parameters supplied to the endpoint. Returns first suitable found object based on params
        Endpoint URL: /driver/get
        :return: JSON of an object or exception status
        """
        if request.method == "GET":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                params = {}  # list of params that we will search by
                # Check if any of the parameters are being passed and then validate them
                if "id" in request.args.keys():
                    params['id'] = helpers.validate_int(
                        request.args.get('id'), 'id')
                if "first_name" in request.args.keys():
                    params["first_name"] = helpers.validate_string(
                        request.args.get('first_name'), 'first_name')
                if "middle_name" in request.args.keys():
                    params["middle_name"] = helpers.validate_string(
                        request.args.get('middle_name'), 'middle_name')
                if "last_name" in request.args.keys():
                    params["last_name"] = helpers.validate_string(
                        request.args.get('last_name'), 'last_name')
                if "dob" in request.args.keys():
                    params["dob"] = helpers.validate_dob(
                        request.args.get('dob'))

                # If no allowed params were passed on - invalidate the request
                if not params:
                    return jsonify({
                        "status_code": 400,
                        "message": "Invalid request"
                    })

                # Get the object based on the given parameters
                driver = Driver.get(params)
                if not driver:
                    return jsonify({
                        "status_code": 404,
                        "message": "Driver not found"
                    })
                return jsonify(driver.serialize())
            except Exception as e:  # Return messages of any exceptions raised during validation
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
コード例 #13
0
def update_driver(driver_id):
    try:
        json_to_validade = request.get_json()
    except Exception as e:
        return make_response(
            jsonify({'return_message': 'JSON Object not found'}), 400)
    # If to validate by test_register_driver_json_not_exist, need to be improved
    if request.get_json() is None:
        return make_response(
            jsonify({'return_message': 'JSON Object not found'}), 400)

    json_to_validade['driver_id'] = driver_id
    errors = driver_schema.validate(json_to_validade)
    if errors:
        return make_response(
            jsonify({
                'return_message':
                'There is some erros in your request see errors_field',
                'errors_field': errors
            }), 400)

    driver = driver_dao.get_driver_by_id(driver_id)
    if driver:
        request_json = request.get_json()
        driver = Driver(request_json.get('name', None),
                        request_json.get('last_name', None),
                        request_json.get('date_of_birth', None),
                        request_json.get('gender_id', None),
                        request_json.get('cnh_type_id', None),
                        request_json.get('own_vehicle', None), driver_id)

        driver = driver_dao.save_driver(driver)
        return jsonify({
            'driver': driver.to_json(),
            'return_message': 'Driver Updated'
        }), 200
    else:
        abort(404, {'message': 'Driver does not exist'})
コード例 #14
0
 def handle(self, *args, **kwargs):
     Loan.objects.all().delete()
     Recurrency.objects.all().delete()
     Transport.objects.all().delete()
     Driver.objects.all().delete()
     ItemDelivery.objects.all().delete()
     Address.objects.all().delete()
     System.objects.all().delete()
     sys = System()
     now_time = utc_to_local(datetime.datetime.now())
     sys.last = now_time
     sys.save()
     dic_sys = {}
     dic_sys[sys.type] = sys.timer
     sys.next = now_time + relativedelta(**dic_sys)
     sys.save()
     for i in range(50):
         transp = Transport()
         transp.save(first_save=True)
         driver = Driver()
         driver.save(first_save=True)
         idelivr = generate_object_item_delivery()
         print(idelivr.lat, idelivr.lng)
コード例 #15
0
ファイル: views.py プロジェクト: araaliFarooq/ride_my_way_api
def register():
    data = request.get_json()
    firstname = data.get("firstname")
    secondname = data.get("secondname")
    username = data.get("username")
    contact = data.get("contact")
    user_category = data.get("user_category")
    password = data.get("password")

    id = len(Users) + 1

    if len(firstname) < 1:
        return jsonify({"message": "first name is missing"}), 400
    if len(secondname) < 1:
        return jsonify({"message": "second name is missing"}), 400
    if len(username) < 1:
        return jsonify({"message": "username is missing"}), 400
    if len(contact) < 1:
        return jsonify({"message": "contact is missing"}), 400
    if len(user_category) < 1:
        return jsonify({"message": "User category is missing"}), 400
    if len(password) < 1:
        return jsonify({"message": "password is missing"}), 400
    """checking is user is a driver or passenger"""
    if user_category == "driver":
        car_type = data.get("car_type")
        reg_num = data.get("reg_num")
        lic_num = data.get("lic_num")

        if len(car_type) < 1:
            return jsonify({"message": "car type is missing"}), 400
        if len(reg_num) < 1:
            return jsonify({"message": "registration number is missing"}), 400
        if len(lic_num) < 1:
            return jsonify({"message": "licence number is missing"}), 400

        new_user = Driver(id, firstname, secondname, username, contact,
                          user_category, car_type, reg_num, lic_num, password)
        Users.append(new_user)
        return jsonify({"message": "New Driver successfully registered"}), 201

    new_user = User(id, firstname, secondname, username, contact,
                    user_category, password)
    Users.append(new_user)
    return jsonify({"message": "New Client successfully registered"}), 201
コード例 #16
0
ファイル: routes.py プロジェクト: kdougla01/f1_project
def addDriver():
    form = AddDriver()
    if form.validate_on_submit():
        # Add Driver details to Driver table in db
        driver = Driver(firstName=form.firstName.data, lastName=form.lastName.data,
                raceNum=form.raceNum.data, nationality=form.nationality.data)
        db.session.add(driver)
        db.session.commit()

        # Queries Driver table to find id of driver, filtered by race number used on driver form
        driverId = Driver.query.filter_by(raceNum=form.raceNum.data).first().id
        # Add Relationship between Driver and Team to team_driver table
        team_driver = Team_driver(team_id=form.team.data, driver_id=driverId)
        db.session.add(team_driver)
        db.session.commit()

        flash('You have successfully added a new driver')
    return render_template('addDriver.html', title='Add Driver', form=form)
コード例 #17
0
def validate_assigning(assigned_type, assigned_id):
    """
    Checks if we can assign this type to this id

    :param assigned_type:
    :param assigned_id:
    :return: list with type and id if passed validation
    :raises Exception: either type or id is invalid
    """
    from app.models import Branch, Driver

    # validate both as ints
    assigned_id = validate_int(assigned_id, 'assigned_id')
    assigned_type = validate_int(assigned_type, 'assigned_type')

    # only allow 1 and 2 to get through
    allowed_types = [1, 2]
    if assigned_type not in allowed_types:
        raise Exception({"status_code": 400, "message": "Invalid assigned_type"})

    if assigned_type == 1:  # 1 = driver
        # check if driver exists
        params = {"id": assigned_id}
        driver = Driver.get(params)
        if driver:
            assigned_id = driver.id
            return [assigned_type, assigned_id]
        else:
            raise Exception({"status_code": 404, "message": "Driver not found"})

    if assigned_type == 2:  # 2 = branch
        # check if branch exists
        params = {"id": assigned_id}
        branch = Branch.get(params)
        if branch:
            occupancy = branch.get_assigned_cars_count(assigned_id)
            if branch.capacity > occupancy:
                return [assigned_type, assigned_id]
            else:
                raise Exception({"status_code": 400, "message": "Branch has reached its capacity"})
        else:
            raise Exception({"status_code": 404, "message": "Branch not found"})
コード例 #18
0
    def driver_delete():
        """
        Deletes a record based on the id
        Endpoint URL: /driver/delete
        :return: JSON successful message or exception response
        """
        if request.method == "DELETE":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                # Validate id parameter passed
                id = helpers.check_missing('args', request, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to delete
                params = {"id": id}
                driver = Driver.get(params)

                # Return 404 if not found the object to delete
                if not driver:
                    return jsonify({
                        "status_code": 404,
                        "message": "Driver not found"
                    })

                # Delete object and return successful message
                driver.delete()
                return jsonify({
                    "status_code": 200,
                    "message": "Driver deleted"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
コード例 #19
0
ファイル: routes.py プロジェクト: OlegLeva/beetroot
def edit(id):
    autotrain = AutoTrain.query.get(id)

    if request.method == 'POST':
        autotrain.train = AutoTrain(
            id=request.form['id_autotrain'],
            truck_id=request.form['truck_license_plate'],
            trailer_id=request.form['trailer_license_plate'],
            driver_id=request.form['driver_name'],
            phone_id=request.form['phone'])
        autotrain.truck = Truck(license_plate=autotrain.train.truck_id)
        autotrain.trailer = Trailer(license_plate1=autotrain.train.trailer_id)
        autotrain.driver = Driver(id=autotrain.train.driver_id)

        # try:
        db.session.commit()

        return redirect("/index")
    # except:
    #     return "При редактировании статьи произошла ошибка"

    else:
        return render_template('edit.html', autotrain=autotrain)
コード例 #20
0
def forge(users):
    click.echo(f"生成{users}条drivers和consigner数据:")
    f = Faker("zh_CN")

    for _ in range(int(users)):
        driver = Driver(username=f.name(),
                        password="******",
                        phone_number=f.phone_number(),
                        email=f.email(),
                        car_type=["大货车", "小货车", "中货车"][randint(0, 2)],
                        account=f.credit_card_number())

        consigner = Consigner(username=f.name(),
                              password="******",
                              phone_number=f.phone_number(),
                              email=f.email(),
                              address=f.address())

        db.session.add(driver)
        db.session.add(consigner)

    db.session.commit()

    click.echo("Done...")
コード例 #21
0
ファイル: routes.py プロジェクト: OlegLeva/beetroot
def add_autotrain():
    if request.method == 'POST':
        train = AutoTrain(id=request.form['id_autotrain'],
                          truck_id=request.form['truck_license_plate'],
                          trailer_id=request.form['trailer_license_plate'],
                          driver_id=request.form['driver_name'],
                          phone_id=request.form['phone'])
        truck = Truck(license_plate=train.truck_id)
        trailer = Trailer(license_plate1=train.trailer_id)
        driver = Driver(id=train.driver_id)

        try:
            db.session.add(train)
            db.session.add(truck)
            db.session.add(trailer)
            db.session.add(driver)
            db.session.commit()

            return redirect("/index")
        except:
            return "Введены неверные данные"

    else:
        return render_template("/add_autotrain.html")
コード例 #22
0
from app.models import Delivery, Driver

driver1 = Driver("John", "Smith")
driver1.insert()

driver2 = Driver("Karen", "Winters")
driver2.insert()

driver3 = Driver("Inez", "Watson")
driver3.insert()

driver4 = Driver("Mark", "Green")
driver4.insert()

delivery1 = Delivery("Softest White Bread")
delivery1.insert()

delivery2 = Delivery("2% Milk")
delivery2.insert()

delivery3 = Delivery("Eggs")
delivery3.insert()

delivery4 = Delivery("Sugar")
delivery4.insert()

delivery5 = Delivery("Brownies")
delivery5.insert()

コード例 #23
0
truck2 = Truck(license_plate="BI8576EI")
truck3 = Truck(license_plate="BI7185AO")
trucks = [truck1, truck2, truck3]
for t in trucks:
    db.session.add(t)
db.session.commit()

trailer1 = Trailer(license_plate1="BI2324XK")
trailer2 = Trailer(license_plate1="BI3844XM")
trailer3 = Trailer(license_plate1="BI4663XK")
trailers = [trailer1, trailer2, trailer3]
for t in trailers:
    db.session.add(t)
db.session.commit()

driver1 = Driver(id="Терещенко Дмитрий")
driver2 = Driver(id="Возный Андрей")
driver3 = Driver(id="Возный Виталий")
drivers = [driver1, driver2, driver3]
for d in drivers:
    db.session.add(d)
db.session.commit()

documemt1 = Document(name="protocol",
                     exp_date=date(2021, 2, 20),
                     truck_id=truck1.license_plate)
documemt2 = Document(name="protocol",
                     exp_date=date(2020, 10, 20),
                     truck_id=truck2.license_plate)
documemt3 = Document(name="protocol",
                     exp_date=date(2020, 11, 20),
コード例 #24
0
 def delete(self, request, *args, **kwargs):
     driver = self.get_object()
     new_driver = Driver()
     new_driver.salary = driver.salary
     new_driver.name = driver.name
     new_driver.surname = driver.surname
     new_driver.type = driver.type
     new_driver.birthdate = driver.birthdate
     new_driver.age = driver.age
     new_driver.photo = driver.photo
     new_driver.save()
     driver.delete()
     return HttpResponseRedirect(self.success_url)
コード例 #25
0
def index():
    db = get_db()
    test = Driver("Rex", "Test driver")

    return render_template('home.html')
コード例 #26
0
    def post(self):
        """Create a new user"""
        reg_info = request.get_json()

        firstName = reg_info.get("firstName")
        secondName = reg_info.get("secondName")
        userName = reg_info.get("userName")
        contact = reg_info.get("contact")
        user_category = reg_info.get("user_category")
        password = reg_info.get("password")

        response = validate.client_validation(firstName, secondName, userName,
                                              contact, user_category, password)

        if response:
            return response

        if user_category == "driver":
            car_type = reg_info.get("car_type")
            reg_num = reg_info.get("reg_num")
            lic_num = reg_info.get("lic_num")

            response2 = validate.driver_validation(
                firstName, secondName, userName, contact, user_category,
                car_type, reg_num, lic_num, password)

            if response2:
                return response2
            # database function to add new driver
            add_new_driver(
                firstName=firstName,
                secondName=secondName,
                userName=userName,
                contact=contact,
                carType=car_type,
                reg_num=reg_num,
                lic_num=lic_num,
                password=password)
            # new driver object
            new_driver = Driver(
                firstName=firstName,
                secondName=secondName,
                userName=userName,
                contact=contact,
                user_category=user_category,
                car_type=car_type,
                reg_num=reg_num,
                lic_num=lic_num,
                password=password)
            return jsonify({"New Driver": new_driver.__dict__}), 200

        # database function to add new client
        add_new_client(
            firstName=firstName,
            secondName=secondName,
            userName=userName,
            contact=contact,
            password=password)
        new_client = User(
            firstName=firstName,
            secondName=secondName,
            userName=userName,
            contact=contact,
            user_category=user_category,
            password=password)
        return jsonify({"New Client": new_client.__dict__}), 200
コード例 #27
0
    name='Perun',
    role='Dps',
    element='Ice',
    weapon='Mega Lance',
    description=
    'Rare blade obtained through core crystals, can be used by any driver')
Praxis = Blade(
    name='Praxis',
    role='Dps',
    element='Water',
    weapon='Mega Lance',
    description=
    'Rare blade obtained through side quest line, can be used by any driver')

Rex = Driver(
    name='Rex',
    description=
    'Main playable character, avalible from the start, main blade is Pyra')
Nia = Driver(
    name='Nia',
    description=
    'Nia is a driver that becomes avalible in chapter 2, she is primarily a healer based driver due to her main blade being Dromarch, a healer blade'
)
Zeke = Driver(
    name='Zeke',
    description=
    'Morag is a driver that becomes avalible in chapter 4, she is primarily a tank based driver due to her story blade being Bridhid, a tank blade'
)
Morag = Driver(
    name='Morag',
    description=
    'Tora is a special driver due to his inability to use normal blades. Because of this, he designed and built his own artificial blade; Poppi'
コード例 #28
0
from app import db
from app.models import Driver, WearableInfo, PhysData

# Driver Database Initialization

# Apple Drivers
d = Driver(device='Apple Watch',
           driverName='Apple Driver1_000',
           version='1.000',
           releaseDate='10/10/2019',
           mostCurrent='Yes')
db.session.add(d)
db.session.commit()

d = Driver(device='Apple Watch',
           driverName='Apple Driver1_001',
           version='1.001',
           releaseDate='10/15/2019',
           mostCurrent='Yes')
db.session.add(d)
db.session.commit()

d = Driver(device='Apple Watch',
           driverName='Apple Driver1_002',
           version='1.002',
           releaseDate='10/24/2019',
           mostCurrent='Yes')
db.session.add(d)
db.session.commit()

# Fitbit Drivers