www.91084.com

GVKun编程网logo

如何在python请求中处理401(未授权)(python请求发生10060报错)

24

此处将为大家介绍关于如何在python请求中处理401的详细内容,并且为您解答有关未授权的相关问题,此外,我们还将为您介绍关于Flutter如何处理401未授权的Dio拦截器、Laravel-Snip

此处将为大家介绍关于如何在python请求中处理401的详细内容,并且为您解答有关未授权的相关问题,此外,我们还将为您介绍关于Flutter 如何处理401 未授权的 Dio 拦截器、Laravel-Snipe IT-401(未经授权)-仅Ajax错误、Python请求:在单个请求中发布JSON和文件、使用 axios 帖子获取 401(未经授权)错误的有用信息。

本文目录一览:

如何在python请求中处理401(未授权)(python请求发生10060报错)

如何在python请求中处理401(未授权)(python请求发生10060报错)

我要做的是从站点获取,如果该请求返回401,请重做我的身份验证摆动(可能已过期),然后重试。但是我不想第三次尝试,因为那将是我的身份验证摆动具有错误的凭据。有没有人有一个很好的方法来执行此操作,而不涉及适当的丑陋代码,最好是在python请求库中,但是我不介意更改。

答案1

小编典典

我认为这并不比这更丑陋:

import requestsfrom requests.auth import HTTPBasicAuthresponse = requests.get(''http://your_url'')if response.status_code == 401:        response = requests.get(''http://your_url'', auth=HTTPBasicAuth(''user'', ''pass''))if response.status_code != 200:    # Definitely something''s wrong

Flutter 如何处理401 未授权的 Dio 拦截器

Flutter 如何处理401 未授权的 Dio 拦截器

老铁记得 转发 ,猫哥会呈现更多 Flutter 好文~~~~

微信群 ducafecat

b 站 https://space.bilibili.com/40...

原文

https://medium.com/@wmnkrisha...

参考

  • https://pub.dev/packages/dio/...
  • https://pub.dev/packages/flut...
  • https://pub.dev/packages/shar...

正文

在本文中,我将解释如何使用 flutter dio (4.0.0)进行网络调用,以及如何在您的 flutter 应用程序中使用刷新令牌和访问令牌来处理授权时处理 401。

在阅读这篇文章之前,我希望你们对颤抖移动应用程序开发有一个基本的了解。

Basic Authentication flow with refresh and access tokens

正如您在上面的图中所看到的,很明显,在身份验证流中使用刷新和访问令牌时的流程是什么。登录后,您将获得两个称为刷新和访问的标记。此访问令牌快速过期(刷新令牌也过期,但是它将比访问令牌花费更多的时间)。当您使用过期的访问令牌发出请求时,响应中会出现状态码 401(未经授权)。在这种情况下,您必须从服务器请求一个新的令牌,并使用有效的访问令牌再次发出上一个请求。如果刷新令牌也已过期,您必须指示用户登录页面并强制再次登录。

Dio class

class DioUtil {
  static Dio _instance;//method for getting dio instance  Dio getInstance() {
    if (_instance == null) {
      _instance = createDioInstance();
    }
    return _instance;
  }

   Dio createDioInstance() {
    var dio = Dio();// adding interceptor    dio.interceptors.clear();
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      return handler.next(options);
    }, onResponse: (response, handler) {
      if (response != null) {
        return handler.next(response);
      } else {
        return null;
      }
    }, onError: (DioError e, handler) async {

        if (e.response != null) {
          if (e.response.statusCode == 401) {//catch the 401 here
            dio.interceptors.requestLock.lock();
            dio.interceptors.responseLock.lock();
            RequestOptions requestOptions = e.requestOptions;

            await refreshToken();
            Repository repository = Repository();
            var accessToken = await repository.readData("accessToken");
            final opts = new Options(method: requestOptions.method);
            dio.options.headers["Authorization"] = "Bearer " + accessToken;
            dio.options.headers["Accept"] = "*/*";
            dio.interceptors.requestLock.unlock();
            dio.interceptors.responseLock.unlock();
            final response = await dio.request(requestOptions.path,
                options: opts,
                cancelToken: requestOptions.cancelToken,
                onReceiveProgress: requestOptions.onReceiveProgress,
                data: requestOptions.data,
                queryParameters: requestOptions.queryParameters);
            if (response != null) {
              handler.resolve(response);
            } else {
              return null;
            }
          } else {
            handler.next(e);
          }
        }

    }));
    return dio;
  }

  static refreshToken() async {
    Response response;
    Repository repository = Repository();
    var dio = Dio();
    final Uri apiUrl = Uri.parse(BASE_PATH + "auth/reIssueAccessToken");
    var refreshToken = await repository.readData("refreshToken");
    dio.options.headers["Authorization"] = "Bearer " + refreshToken;
    try {
      response = await dio.postUri(apiUrl);
      if (response.statusCode == 200) {
        LoginResponse loginResponse =
            LoginResponse.fromJson(jsonDecode(response.toString()));
        repository.addValue(''accessToken'', loginResponse.data.accessToken);
        repository.addValue(''refreshToken'', loginResponse.data.refreshToken);
      } else {
        print(response.toString()); //TODO: logout
      }
    } catch (e) {
      print(e.toString()); //TODO: logout
    }
  }
}

以上是完整的课程,我将解释其中最重要的部分。

主要是,正如您在 createDioInstance 方法中看到的,您必须添加一个拦截器来捕获 401。当 401 发生在 error: (DioError e,handler) async {}被调用时。所以你的内心

  1. Check the error code(401), 检查错误代码(401) ,
  2. Get new access token 获取新的访问令牌
await refreshToken();

上面的代码将调用 refreshToken 方法并在存储库中存储新的刷新和访问令牌。(对于存储库,您可以使用 secure storage or shared preferences)

  1. 复制前一个请求并设置新的访问令牌
RequestOptions requestOptions = e.requestOptions;
Repository repository = Repository();
var accessToken = await repository.readData("accessToken");
final opts = new Options(method: requestOptions.method);
dio.options.headers["Authorization"] = "Bearer " + accessToken;
dio.options.headers["Accept"] = "*/*";
  1. Make the previous call again
final response = await dio.request(requestOptions.path,
    options: opts,
    cancelToken: requestOptions.cancelToken,
    onReceiveProgress: requestOptions.onReceiveProgress,
    data: requestOptions.data,
    queryParameters: requestOptions.queryParameters);

一旦收到回复,就 call

handler.resolve(response);

然后响应将被发送到您调用 api 的位置,如下所示。

var dio = DioUtil().getInstance();
final String apiUrl = (BASE_PATH + "payments/addNewPayment/");
var accessToken = await repository.readData("accessToken");
dio.options.headers["Authorization"] = "Bearer " + accessToken;
dio.options.headers["Accept"] = "*/*";//response will be assigned to response variable
response = await dio.post(apiUrl, data: event.paymentRequest.toJson());

Thats all. happy coding :)


© 猫哥

https://ducafecat.tech/

https://github.com/ducafecat

往期

开源

GetX Quick Start

https://github.com/ducafecat/...

新闻客户端

https://github.com/ducafecat/...

strapi 手册译文

https://getstrapi.cn

微信讨论群 ducafecat

系列集合

译文

https://ducafecat.tech/catego...

开源项目

https://ducafecat.tech/catego...

Dart 编程语言基础

https://space.bilibili.com/40...

Flutter 零基础入门

https://space.bilibili.com/40...

Flutter 实战从零开始 新闻客户端

https://space.bilibili.com/40...

Flutter 组件开发

https://space.bilibili.com/40...

Flutter Bloc

https://space.bilibili.com/40...

Flutter Getx4

https://space.bilibili.com/40...

Docker Yapi

https://space.bilibili.com/40...

Laravel-Snipe IT-401(未经授权)-仅Ajax错误

Laravel-Snipe IT-401(未经授权)-仅Ajax错误

如何解决Laravel-Snipe IT-401(未经授权)-仅Ajax错误?

我是Laravel的新手,并且正在配置Snipe-使用laravel https://snipe-it.readme.io/docs的IT工具。 我的配置如下 Windows OS,Wamp Server-3.2.3,Laravel- 6.18.43,PHP-7.3.21版本。登录正在工作,我试图添加一些产品。它添加到数据库中。但是在列出所有项目时却出现401错误

获取http:// localhost / api / v1 / companies?search =&order = asc&offset = 0&limit = 20&searchable%5B%5D = name 401(未经授权)-我认为它是ajax调用。

这是我的Apache配置文件

  <VirtualHost *:80>
     ServerName localhost
     ServerAlias localhost
     DocumentRoot "${INSTALL_DIR}/www/snipe/public"
     <Directory "${INSTALL_DIR}/www/snipe/public/">
        Allow From All
        Options +Indexes
        AllowOverride All
        Require all granted
     </Directory>
  </VirtualHost>

这是视图/刀片

          <table data-columns="{{ 
         \App\Presenters\CompanyPresenter::dataTableLayout() }}"
          data-cookie-id-table="companiesTable"
          data-pagination="true"
          data-id-table="companiesTable"
          data-search="true"
          data-side-pagination="server"
          data-show-columns="true"
          data-show-export="true"
          data-show-refresh="true"
          data-sort-order="asc"
          id="companiesTable"data-url="{{ route(''api.companies.index'') }}"
          data-export-options=''{
                    "fileName": "export-companies-{{ date(''Y-m-d'') }}","ignoreColumn": ["actions","image","change","checkBox","checkincheckout","icon"]
                    }''>

        </table>

路线

  Route::resource(''components'',''ComponentsController'',[
        ''names'' =>
            [
                ''index'' => ''api.components.index'',''show'' => ''api.components.show'',''store'' => ''api.components.store'',''update'' => ''api.components.update'',''destroy'' => ''api.components.destroy''
            ],''except'' => [''create'',''edit''],''parameters'' => [''component'' => ''component_id'']
    ]
); // Components resource

控制器

  /**
 * Returns view to display listing of companies.
 *
 * @return \Illuminate\Contracts\View\View
 * @throws \Illuminate\Auth\Access\AuthorizationException
 */
public function index()
{
    Log::error(''CompaniesController::Index'');
    $this->authorize(''view'',Company::class);
    Log::error(''CompaniesController::Index:Authorized'');
    return view(''companies/index'');
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Python请求:在单个请求中发布JSON和文件

Python请求:在单个请求中发布JSON和文件

我需要进行API调用,以上传文件以及带有有关文件详细信息的JSON字符串。

我正在尝试使用python请求库来执行此操作:

import requestsinfo = {    ''var1'' : ''this'',    ''var2''  : ''that'',}data = json.dumps({    ''token'' : auth_token,    ''info''  : info,})headers = {''Content-type'': ''multipart/form-data''}files = {''document'': open(''file_name.pdf'', ''rb'')}r = requests.post(url, files=files, data=data, headers=headers)

这将引发以下错误:

    raise ValueError("Data must not be a string.") ValueError: Data must not be a string

如果我从请求中删除“文件”,则它可以工作。
如果我从请求中删除了“数据”,它将起作用。
如果我不将数据编码为JSON,则可以使用。

因此,我认为错误与在同一请求中发送JSON数据和文件有关。

关于如何使它工作的任何想法?

答案1

小编典典

不要使用json进行编码。

import requestsinfo = {    ''var1'' : ''this'',    ''var2''  : ''that'',}data = {    ''token'' : auth_token,    ''info''  : info,}headers = {''Content-type'': ''multipart/form-data''}files = {''document'': open(''file_name.pdf'', ''rb'')}r = requests.post(url, files=files, data=data, headers=headers)

请注意,这不一定是您想要的,因为它将成为另一个表单数据部分。

使用 axios 帖子获取 401(未经授权)错误

使用 axios 帖子获取 401(未经授权)错误

如何解决使用 axios 帖子获取 401(未经授权)错误?

我使用 Reactjs 制作了注册和登录页面。如果我使用 Postman,POST 请求工作正常,但如果我尝试使用 axios 发送请求,我总是收到 401 (Unauthorized) 错误。这是我的注册代码:

axios.post(''http://localhost:1338/users/'',{
headers: { ''Content-Type'': ''application/json''},username: this.state.userName,email: this.state.userEmail,password: this.state.userPassword,confirmed: true,blocked: false

})
.then((response) => {
    console.log(response);
  },(error) => {
    console.log(error);
  });
}

我检查了 state 变量实际上是正确的,我什至尝试将字符串直接硬编码为 usernameemailpassword。但无论如何它都会抛出同样的错误。可能有什么问题?

编辑:

我得到了在浏览器中检查 Request Headers 的建议,当我尝试注册时,我得到两个实例:

enter image description here

我检查了请求标头,发现有 Authorization: Bearer null。但是在注册时我不会发送授权标头。我得到了清除 cookie 和 localstorage 的建议,我该怎么做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

关于如何在python请求中处理401未授权的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Flutter 如何处理401 未授权的 Dio 拦截器、Laravel-Snipe IT-401(未经授权)-仅Ajax错误、Python请求:在单个请求中发布JSON和文件、使用 axios 帖子获取 401(未经授权)错误等相关知识的信息别忘了在本站进行查找喔。

本文标签: