django从视图中调用外部api

时间:2016-02-11 18:38:51

标签: django django-class-based-views

我试图从基于类的视图调用外部api。 目前我有以下视图调用API。不过,目前我只是使用class ViewController: UIViewController,CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestAlwaysAuthorization() } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .AuthorizedWhenInUse: updateMap() break case .AuthorizedAlways: updateMap() // write your map related code here break default: break } } func updateMap() { let currentLocationCoo = locationManager.location?.coordinate if let locationCoo = currentLocationCoo{ mapView.region = MKCoordinateRegionMake(CLLocationCoordinate2D(latitude: locationCoo.latitude, longitude: locationCoo.longitude), MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)) print("location ni nil") }else{ mapView.region = MKCoordinateRegionMake(CLLocationCoordinate2D(latitude: 52.05695, longitude: 14.50575), MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)) } let defaultAnnotation = MKPointAnnotation() defaultAnnotation.coordinate = mapView.region.center defaultAnnotation.title="Center" defaultAnnotation.subtitle="This is!" mapView.addAnnotation(defaultAnnotation) mapView.showsUserLocation=true mapView.showsBuildings=true mapView.userTrackingMode = .None } } 调用API,它会返回数据,但不会保存。

如何将视图中modelform中使用的模型传递给api函数,以便将返回的数据保存到相关用户。 (即我需要在CBV中覆盖哪种方法)。

另外,在django中调用外部api的最佳方法是什么(从表单完成开始)。目前API往返需要5-10秒,目前它的设置方式会延迟下一页加载量。

api(username, password)

型号:

class SupplierOnlineAccountView(CreateView):
    form_class = SupplierOnlineAccountForm
    template_name = 'standard_form.html'
    success_url = '../contacting'

    def form_valid(self, form):
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        api(username, password)
        return super().form_valid(form)

1 个答案:

答案 0 :(得分:1)

def form_valid(self, form):
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    self.object = form.save()
    api(username, password,self.object)
    return super().form_valid(form)

您必须将title,first_name,last_name字段更改为blank = True,以便在api调用之前保存,然后传递已保存的模型。

API的等待时间问题,这是像芹菜这样的队列的典型异步任务。保存表单,然后将任务卸载到队列,该队列在另一个线程(或进程或机器)上运行。然后django不必等到api返回,并发送响应。