Django rest框架 - 在过滤时提高异常/处理空结果

时间:2017-04-06 06:22:49

标签: django-rest-framework

我有一个用户个人资料类,正在检查用户是否存在以及是否不想创建该用户。

我正在使用userprofile的过滤器类,以便客户端可以调用:

http://localhost:8000/users/?email=a@b.com

如果结果为空,则会创建一个包含电子邮件地址的用户。

有没有办法拦截查询结果并在其为空时引发异常并处理创建用户的异常。 如果有更好的方法也希望得到纠正。

/* Display real time information for a specific connection by scraping mobile.bahn.de */

require_once("simple_html_dom.php");

function departure_in_seconds($from, $to, $connection_number){

      // html on mobile.bahn.de is weird. So wi
      $row_number = ($connection_number+1) * 2 - 2;

      $date = date('d.m.y');
      $time = date('H:i');

      // set post fields
      $post = [
        'queryPageDisplayed' => 'yes',
        'REQ0JourneyStopsS0A'=> 1,
        'REQ0JourneyStopsS0G' => $from,
        'REQ0JourneyStopsS0ID' => '',
        'locationErrorShownfrom' => 'yes',
        'REQ0JourneyStopsZ0A' => 1,
        'REQ0JourneyStopsZ0G' => $to,
        'REQ0JourneyStopsZ0ID' => '',
        'locationErrorShownto' => 'yes',
        'REQ0JourneyDate' => $date,
        'REQ0JourneyTime' => $time,
        'existOptimizePrice' => 1,
        'REQ0HafasOptimize1' => '0:1',
        'rtMode' => 12,
        'existRTMode' => 1,
        'immediateAvail' => 'ON',
        'start' => 'Suchen'
      ];

      /* post form fields to mobile.bahn.de */
      $html = url_to_dom('https://mobile.bahn.de/bin/mobil/query.exe/dox', $post);

      /* Scrape the correct train connection from HTML */
      $connection = str_get_html($html->find('.scheduledCon',$row_number));

      /* Find departure time information in connection HTML snippet */
      $departure_time_string = $connection->find('.bold',0)->plaintext;

      /* Find delay information in connection HTML snippet */
      $delay_string =  $connection->find('.okmsg',0);
      $delay = preg_replace("/[^0-9]/","",$delay_string);
      $delay_seconds = $delay*60;

      /* Calculate the time until departure in seconds. */
      $departure_in_seconds = strtotime($departure_time_string) + $delay_seconds - strtotime('now');

      /* Find link to train connection detail information page */
      $connection_details_url = ($connection->find('a',0)->href);

      /* THIS DOES NOT WORK! WHY?? The response is not the correct HTML */
      /* Scrape this connection detail url */
      $connection_details_html = url_to_dom($connection_details_url);
      echo $connection_details_html;


      /* Find the trainline in the HTML snippet */
      $trainline = $connection_details_html->find('.motSection',0);

      /* Return all information */
      return $departure_time_string.' Delay:'.$delay.' Train line:'.$trainline;

}

function url_to_dom($href, $post = false) {
    /*store temporary cookie files */
    $cookie_jar = tempnam('/tmp','cookie');

    $curl = curl_init();

    /* if $post is set sent this posdt fields as a post request */
    if( $post ){
      curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
      curl_setopt($curl, CURLOPT_POST, true);
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar);
    curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
    curl_setopt($curl, CURLOPT_URL, $href);

    $str = curl_exec($curl);
    curl_close($curl);
    // Create a DOM object
    $dom = new simple_html_dom();
    // Load HTML from a string
    $dom->load($str);

    return $dom;
}

echo departure_in_seconds('Langenfelde', 'Altona', 0).'<br>';

感谢任何帮助。

由于 阿南德

1 个答案:

答案 0 :(得分:0)

Django Rest Framework提供了默认禁用的功能。也许它可以为您提供另一种方法来解决您的问题:file.seek(offset)

另一方面,如果您确实需要通过带有查询字符串的GET请求创建用户,则可以使用来自django-filters的MethodFilter,例如:

class UserFilters(FilterSet):
    user = MethodFilter(action='filter_user')

    class Meta:
        model = User
        fields = ['user']

    def filter_user(self, queryset, value):
        if not value:
            # Here Raise Exception
        else:
            # Check if the user exists, if not create it
            users = queryset.filter(Q(username=value) | Q(email=value))
            if not users.exists:
                user = User.objects.create(...)
                return queryset.filter(pk=user.id)
            else:
                return users

希望这可以帮到你。我并不十分确定它是以这种方式运作的,但它是这个想法。

就个人而言,我建议您尝试通过更合适的请求(如POST或PUT)执行该任务,并使用相应的方法进行管理。