Мое реактивное приложение не может запускать запросы PUT и POST http на мой RESTful API, созданный из web2py. - PullRequest
0 голосов
/ 19 октября 2018

Мое приложение-ответчик не может запустить запрос HTTP PUT и POST, оно ПОЛУЧАЕТСЯ, но для PUT оно не может, вот мой RESTful API, созданный с использованием web2py.API работает, потому что когда я использую curl, все запросы запускаются правильно.Вот API RESTful

@request.restful()
def api():
 response.view = 'generic.'+request.extension
 def GET(*args,**vars):
     patterns = [
         "/trip[trip]",                      # endpoint to get all client trips
         "/trip/{trip.id}",                  # endpoint to get trip details by id
         "/self[self_driver_trip]",          # endpoint to get all self trips
         "/self/{self_driver_trip.id}",      # endpoint to get a particular self trip
         "/driver-trip[driver_trip]",        # endpoint to get all client trips
         "/driver-trip/{driver_trip.id}",    # endpoint to get a particular client trip
         "/indi-trip[individual_trip]",      # endpoint to get all trips
         "/indi-trip/{individual_trip.id}",  # endpoint to get an individual trip
         "/get_companies[company]",          # endpoint to get all companies
        "/company/{company.id}",            # endpoint to get company details
        "/driver[driver]",                  # endpoint to get all drivers
        "/driver/{driver.id}",              # endpoint to get driver details
        "/get_vehicles[vehicle]",           # endpoint to get all vehicles
        "/vehicle/{vehicle.id}"             # endpoint to get vehicle details
    ]
    parser = db.parse_as_rest(patterns, args, vars)
    if parser.status == 200:
        print(response.json(parser.response))
        return response.json(parser.response)
    else:
        raise HTTP(parser.status, parser.error)
 def POST(pattern, **vars):
    if pattern == 'self':                                               # Add a new self trip
        print("self")
        return dict(db.self_driver_trip.validate_and_insert(**vars))
    elif pattern == 'driver-trip':                                      # Add a new driver trip
        print('driver_trip')
        return dict(db.driver_trip.validate_and_insert(**vars))
    elif pattern == 'trip':                                             # Add new a trip
        print('we are here')
        return response.json(dict(db.trip.validate_and_insert(**vars)))
    elif pattern == 'indi-trip':                                        # Add a new individual trip
        print('indi-trip')
        return dict(db.individual_trip.validate_and_insert(**vars))
    elif pattern == 'company':                                          # Add a new company
        print('company')
        return dict(db.company.validate_and_insert(**vars))
    elif pattern == 'driver':                                           # Add a new driver
        print('driver')
        return dict(db.driver.validate_and_insert(**vars))
    elif pattern == 'vehicle':                                          # Add a new vehicle
        print('vehicle')
        return dict(db.vehicle.validate_and_insert(**vars))
    elif pattern == 'self_validate':                                    # Validate a self user by phone number
        phone = request.vars.phone
        license_number = request.vars.license_number
        vehicle_id = request.vars.vehicle_id
        trip = db((db.self_driver_trip.phone == phone) & (db.self_driver_trip.license_number == license_number)
                  &(db.self_driver_trip.vehicle_id == vehicle_id)).select().first()
        if trip is None:
            return response.json(dict(message= 'SELF_NOT_EXIST')), 400
        elif trip.status != 'In Progress':
            return response.json(dict(message='SELF_COMPLETED')), 400
        else:
            return response.json(trip), 200

    elif pattern == 'company_validate':                                # validate a company(check if it exists)
        company = request.vars.company
        comp = db(db.company.name==company).select().first()
        if comp is None:
            return response.json(dict(message= 'Invalid Company Name')), 400
        else:
            print('company validated')
            return response.json(dict(message='Success',
                                      comp_id= comp.id)), 200
    elif pattern == 'driver_validate':                                  # validate driver (check if record exists)
        company_id = request.vars.company_id
        print(company_id)
        password = request.vars.password
        print(password)
        driver = db((db.driver.company_id == company_id)&(db.driver.password==password)).select().first()
        if driver is None:
            return response.json(dict(message='Sorry, the credentials you entered are not valid')), 400
        elif driver.status != "Available":
            current_trip = driver.current_trip
            print(current_trip)
            current_trip_type = driver.current_trip_type
            print(current_trip_type)
            return response.json(dict(message='DRIVER_UNAVAILABLE',current_trip=current_trip, current_trip_type=current_trip_type))
        else:
            return response.json(dict(message='Welcome to Mercantile', driver_id=driver.id, company_id=driver.company_id))

    elif pattern == 'vehicle_validate':                                 # validate vehicle
        vehicle_id = request.vars.vehicle_id
        current_mileage = request.vars.current_mileage
        vehicle = db(db.vehicle.id == vehicle_id).select().first()
        if vehicle is None:
            return response.json(dict(message='Sorry, the car information you entered is not valid')), 400
        elif vehicle.status != 'Available':
            return response.json(dict(message='Sorry, car is already in use')), 400
        elif current_mileage < int(vehicle.current_mileage):
            return response.json(dict(message='MILEAGE_LOWER')), 400
        elif (current_mileage - int(vehicle.current_mileage)) > 7:
            return response.json(dict(message='MILEAGE_GREATER')), 400
        else:
            return response.json(dict(
                        message= 'Vehicle Valid',
                        vehicle_id= vehicle.vehicle_id,
                        current_mileage= vehicle.current_mileage )), 200

    else:
        raise HTTP(400)
  def PUT(pattern, record_id, **vars):
    if pattern == 'vehicle_mileage_update':
        vehicle = db(db.vehicle.id == record_id).select().first()
        current_mileage = request.vars.current_mileage
        db_mileage = int(vehicle.current_mileage)
        # TRIP LIMIT
        if (current_mileage - db_mileage) > 500:
            return response.json(dict(message='MILEAGE_OVERLOAD')), 400
        elif current_mileage < db_mileage:
            return response.json(dict(message='MILEAGE_UNDERLOAD')), 400
        else:
            return db(db.vehicle.id == record_id).update(**vars), 200
    else:
        print("reached here in PUT")
    db(db[pattern].id == record_id).update(**vars)

  def DELETE(table_name, record_id):
    return db(db[table_name].id==record_id).delete()
return dict(GET=GET, POST=POST, PUT=PUT, DELETE=DELETE)

А теперь это мой фрагмент кода из моего собственного реактивного приложения, которое должно сделать запрос HTTP PUT для обновления таблицы с именем trip

let response = await fetch(
                    API_URL+'/trip',
                    {
                        method: 'POST',
                        body: JSON.stringify({
                            driver_id: this.props.navigation.state.params.driver_id,
                            start_mileage: parseInt(this.state.start_mileage),
                            client: this.state.client,
                            comp_id: this.state.comp_id,
                            vehicle_id: this.state.vehicle_id,
                            start_date: new Date().toLocaleString(),
                            departure: this.state.departure,
                            trip_type: this.state.trip_type,
                            departure_geo_lat: this.state.dep_latitude,
                            departure_geo_long: this.state.dep_longitude
                        }),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                )

и запрос PUT

let response = await fetch(
                            API_URL+'/driver/'+this.state.driver_id,
                            {
                                method: "PUT",
                                body: JSON.stringify({
                                    status: "On a Trip",
                                    current_trip_type: "Client",
                                    current_trip: responseJson.id 
                                }),
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            }
                        )

ПРИМЕЧАНИЕ: это работает, когда я использую API колбы, но я хотел создать бэкэнд, используя web2py, поэтому я решил сделать RESTful API в web2py даже для моего приложения для Android, чтобыиспользовать.Почему это не может работать с web2py

...