urllib2: Basic Authentication

告别CPU空转!用STC8的SPI+DMA高效驱动上百颗WS2812B灯珠 本文详细解析了如何利用STC8单片机的SPI+DMA外设高效驱动WS2812B全彩灯珠,解决传统软件延时驱动方式在长灯带应用中的性能瓶颈。通过硬件方案设计、数据格式转换和DMA传输配置,实现高达400Hz的刷新率和低于5%的CPU占用率,适用于大规模灯光项目。 阅读详情

http://www.voidspace.org.uk/python/articles/authentication.shtml#base64

http://kentsjohnson.com/kk/00010.html


Basic Authentication is part of the HTTP protocol. When you browse to a web site that uses basic auth, the browser pops up a dialog asking for your username and password. You supply credentials to the browser; your credentials are included with every subsequent request to the same web site.

To authenticate using basic authentication you must configure an opener with an HTTPBasicAuthHandler. The handler itself must be configured with the authentication realm, server address, username and password. Here is an example:

# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password('realm', 'example.com', 'username', 'password')
opener = urllib2.build_opener(auth_handler)
The open() method of the returned opener can be used to read pages that require authentication:
data = opener.open('http://example.com/my/protected/page.html').read()

You can also install the opener globally so it will be used with urlopen():
urllib2.install_opener(opener)
data = urllib2.urlopen('http://example.com/my/protected/page.html').read()

Note: the realm is defined by the webserver that is requesting authentication. When you use your browser to log on with basic auth, the browser dialog will say something like "Enter user name and password for 'realm' at http://example.com." The realm that is displayed in the browser is the value you must use to configure the HTTPBasicAuthHandler.


首先可以用如下代码判断是否可以读取该网页的url:

import urllib
#print urllib.urlopen('http://www.google.com').read()

theurl = urllib.urlopen('http://mail.163.com/')
print 'http status:', theurl.getcode()

for line in theurl: # 就像在操作本地文件
    print line,
theurl.close()

可以用如下代码判断访问该网页的url是否需要authentication:

import urllib2

theurl = 'https://cpanel.net/'
req = urllib2.Request(theurl)
try:
    print 'urlopen begin'
    handle = urllib2.urlopen(req)
    print 'urlopen finish'
except IOError, e:
    if hasattr(e, 'code'):
        if e.code != 401:
            print 'We got another error'
            print e.code
        else:
            print 'yes'
            print e.headers
            print e.headers['www-authenticate']
    else:
        print r'the string "code" is not in e'
        print e
else:
    print 'this url can be accessed'

可以用如下代码进行authentication(自己未验证成功):

import urllib2
import sys
import re
import base64
from urlparse import urlparse


theurl = 'http://api.minicloud.com.cn/statuses/friends_timeline.xml'
# if you want to run this example you'll need to supply
# a protected page with your username and password


username = 'xxx'
password = 'xxx'            # a very bad password


req = urllib2.Request(theurl)
try:
    handle = urllib2.urlopen(req)
except IOError, e:
    # here we *want* to fail
    pass
else:
    # If we don't fail then the page isn't protected
    print "This page isn't protected by authentication."
    sys.exit(1)


if not hasattr(e, 'code') or e.code != 401:
    # we got an error - but not a 401 error
    print "This page isn't protected by authentication."
    print 'But we failed for another reason.'
    sys.exit(1)


#!!!the following code is used to get scheme and realm which however are not used
#getting scheme and realm begin
    
authline = e.headers['www-authenticate']
# this gets the www-authenticate line from the headers
# which has the authentication scheme and realm in it


authobj = re.compile(
    r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',
    re.IGNORECASE)
# this regular expression is used to extract scheme and realm
matchobj = authobj.match(authline)


if not matchobj:
    # if the authline isn't matched by the regular expression
    # then something is wrong
    print 'The authentication header is badly formed.'
    print authline
    sys.exit(1)


scheme = matchobj.group(1)
realm = matchobj.group(2)
# here we've extracted the scheme
# and the realm from the header
if scheme.lower() != 'basic':
    print 'This example only works with BASIC authentication.'
    sys.exit(1)
    
#get scheme and realm finish




base64string = base64.encodestring(
                '%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
    handle = urllib2.urlopen(req)
except IOError, e:
    # here we shouldn't fail if the username/password is right
    print "It looks like the username or password is wrong."
    sys.exit(1)
thepage = handle.read()


 

告别理论!手把手教你用Vivado 2020.2为ZYNQ PL端打造一个AXI4-Full读写DDR的IP核 本文详细介绍了如何使用Vivado 2020.2为ZYNQ PL端创建AXI4-Full主控IP核,实现高效读写DDR内存的实战指南。通过环境配置、IP核创建、系统集成到软件调试的全流程讲解,帮助开发者快速掌握AXI4-Full协议在ZYNQ平台上的应用,提升PL与PS协同工作的数据传输效率。 阅读详情

相关推荐

开关电源EMI优化秘籍:三明治绕法如何让你的产品通过认证测试

本文深入解析了开关电源EMI优化中的三明治绕法,详细阐述了其通过改变绕组排布来减小初次级寄生电容、降低共模噪声的核心机理。文章提供了从绕制结构选择、绝缘安规处理到实测验证的全流程实战指南,帮助工程师有效利用这一工艺,提升产品通过CCC、CE等EMI认证测试的成功率。

tcp8optimizer的博客 711

Google各国网址

=============$旧文$留此存照=============== 巴西 www.google.com.br 瑞士 www.google.ch 荷兰 www.google.nl 澳大利亚 www.google.com.au 印度 www.google.co.in 罗马尼亚 www.google.ro 泰国 www.google.co.th 沙特阿拉伯 www.

从Web开始... 2万+

避坑指南:SpringBoot对接拉卡拉支付常见问题与解决方案(含SDK 1.0.6配置技巧)

本文是一份SpringBoot项目对接拉卡拉支付的实战避坑指南。针对SDK 1.0.6版本,详细剖析了从依赖管理、多环境配置、SDK初始化到支付请求构建、回调验签及生产监控的全流程常见问题,并提供了经过验证的解决方案与配置技巧,旨在帮助开发者高效、稳定地集成支付功能。

k5l6m的博客 342

开源项目 `basic-auth` 常见问题解决方案

`basic-auth` 是一个用于解析 HTTP 请求中基本认证(Basic Authentication)授权头字段的 Node.js 模块。它可以帮助开发者轻松地从请求中提取用户名和密码,并进行相应的验证。该项目的主要编程语言是 JavaScript,适用于 Node.js 环境。 ## 新手使用注意事项及解决方案 ### 1. 安装问题 **问题描述**:新手在安装 `basic-a

gitblog_00208的博客 476

【毕设课设】基于YOLO v3与LSTM的水位智能识别系统(附完整源码+数据集)

本文详细介绍了基于YOLO v3与LSTM的水位智能识别系统的完整实现方案。该系统通过YOLO v3精准定位水位尺数字,结合LSTM-OCR进行序列识别,并融合霍夫变换检测刻度线,实现高精度水位自动读取。项目提供了从环境搭建、模型训练到集成部署的全流程指南,并附有完整源码和数据集,是理想的毕设课设实战项目。

php55的博客 614

人工智能(AI)简史:推动新时代的科技力量

人工智能(AI,Artificial Intelligence)是计算机科学的一个分支,旨在研究和开发可以模拟、扩展或增强人类智能的系统。它涉及多种技术和方法,包括机器学习、深度学习、自然语言处理(NLP)、计算机视觉、专家系统等。

qq_17153885的博客 1万+

39.BasicAuthentication认证

BasicAuthentication认证介绍 BasicAuthentication使用HTTP基本的认证机制 通过用户名/密码的方式验证,通常用于测试工作,尽量不要线上使用 用户名和密码必须在HTTP报文头部,为 Authorization 属性提供值为 Basic amFjazpmZWl4dWVsb3ZlMTAw 的方式提供 其中 Basic 字符串是键,后面的一串乱码是通过base6...

木子七的博客 531

5分钟搞定Google Custom Search API申请:从注册到获取CX Key全流程

本文详细介绍了如何快速申请和配置Google Custom Search API,从Google Cloud项目创建、启用计费、获取API Key,到在Programmable Search Engine控制台创建自定义搜索引擎并获取关键的CX Key,提供了全流程实战指南。文章还包含安全配置建议、API调用测试方法及前端与后端的集成代码示例,帮助开发者高效实现网站或应用的智能搜索功能。

weixin_29227585的博客 1712

Python中利用urllib2使用POST方式上传文件,并解决Authorization问题

为什么80%的码农都做不了架构师?>>> ...

weixin_34041003的博客 694

GprMax正演模拟:为什么你的反射波‘消失’了?可能是直达波在捣鬼(附Python后处理脚本)

本文深入探讨了GprMax正演模拟中反射波信号被直达波淹没的现象,并提供了Python后处理脚本的实战指南。通过时域置零、自适应增益控制、频域滤波等多种技术,有效增强反射波信号,帮助用户解决探地雷达模拟中的常见问题。文章还包含详细的代码示例和效果评估方法,适合GPR数据处理的研究人员和工程师参考。

weixin_29305313的博客 236

视频帧插学习(三):ema-vfi代码拆解和分析

video interp EMA-VFI

mikhailbran的博客 719

【权限管理】Basic 认证(Basic Authentication)

Basic 认证(Basic Authentication)是一种简单的 HTTP 协议认证方式,它通过将用户名和密码与 HTTP 请求一起发送来验证用户身份。这种方式的特点是简单实现,但安全性较低,因此在使用时通常需要配合 HTTPS 来确保数据的安全性。

IT古董 2775

YOLO11涨点优化:训练技巧 | 使用标签平滑(Label Smoothing)配合余弦退火学习率,防止过拟合,稳步提点

摘要: YOLO11凭借动态卷积核调度、自适应特征融合等创新成为2026年目标检测主流,但面临训练集过拟合问题。文章聚焦两种零推理开销的正则化技巧:标签平滑(Label Smoothing)和余弦退火学习率(Cosine Annealing LR)。标签平滑通过软化硬标签(如将[1,0]改为[0.9,0.1])防止模型过度自信,代码中通过label_smoothing=0.1一键启用;余弦退火则以平滑的余弦曲线调整学习率(cos_lr=True),避免阶梯衰减的震荡。两者组合可显著缩小YOLO11训练与验证

2601_95807009的博客 48

python Basic Authentication

有时候我们需要python解析一些页面,实现自动化监控的功能。而这些页面一般需要用户输入username,password进行基本的验证,这时就需要我们使用python基本的认证功能。现已python抓取dubbo-admin的服务页面进行举例: # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefau

heymysweetheart的专栏 3032

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

访问需要HTTP Basic Authentication认证的资源的各种语言的实现

无聊想调用下嘀咕的api的时候,发现需要HTTP Basic Authentication,就看了下。 什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。 在你访问一个需要HTTP Basic Authentication的URL的时候,如果你没有提供用户...

diandi5157的博客 246

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

HTTP Basic Authentication

Client端发送请求, 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:1. 在请求头中添加Authorization: Authorization: "Basic 用户名和密码的base64字符串" 其中, 用户名和密码中间先用:号隔开, 然后做base64编码, 如'Basic dGVzdDpwd2Q=' header的...

诸葛建站 114

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

python中urllib2模块 HTTPBasicAuthHandler认证 HTTPError bug

 系统winxp python 版本 2.6.6  用python 的urllib2模块做HTTP Basic Access Authentication 认证超过6次后抛出HTTPError   import urllib2 import os import re import time userAgent="Mozilla/5.0 (Windows; U; Windows N...

bnmcvzx 481

使用 urllib 进行身份验证

如下图,有些网站需要使用用户名密码才可以登录,我们可以使用HTTPBasicAuthHandler()来实现 from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener username = 'username' password = 'passw...

weixin_30340617的博客 520

python模拟登录http basic authentication网站

当访问需要认证的网站时会提示输入正确的用户和密码如果密码错误会返回401的状态码401 Authorization Required通过python脚本模拟登录#!/usr/bin/python #-*-coding:utf-8-*- importurllib2 #登录的用户名和密码 username="root" password="redhat" url...

weixin_33874713的博客 514

爬虫---3、Urllib库的基本使用

官方文档地址:https://docs.python.org/3/library/urllib.html 转载自:https://www.2cto.com/kf/201801/714859.html 什么是 Urllib 库?  urllib 库 是 Python 内置的 HTTP 请求库。urllib 模块提供的上层接口,使访问 www 和 ftp 上的数据就像访问本地文件一样。有以下...

大发的博客 536

HTTP基本认证(Basic Authentication) 实践

服务端 nodejs var http = require('http') var server = http.createServer() server.listen(80, function () { console.log('running...') }) server.on('request', function (req, res) { console.log(...

知识改变一切 3583

Basic Authentication - Authentication with Python(翻译草稿)

BasicAuthentication AuthenticationwithPython 原文链接: http://www.voidspace.org.uk/python/articles/authentication.shtml#so-let-s-do-it Note ThereisaFrenchtranslationofthisarticle-A...

weixin_30621919的博客 319

python 访问需要HTTP Basic Authentication认证的资源

为什么80%的码农都做不了架构师?>>> ...

weixin_34050005的博客 925

python模拟登录网站_python模拟登录http basic authentication网站

当访问需要认证的网站时会提示输入正确的用户和密码如果密码错误会返回401的状态码401 Authorization Required通过python脚本模拟登录#!/usr/bin/python#-*-coding:utf-8-*-import urllib2#登录的用户名和密码username = "root"password = "redhat"url="http://192.168.209....

weixin_39633774的博客 354

PYTHON实现HTTP基本认证(BASIC AUTHENTICATION)

参考: http://www.voidspace.org.uk/python/articles/authentication.shtml#id20 http://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81 #! /usr/bin/env python # -*-coding:utf-8-*- ...

weixin_30552635的博客 866

Basic Auth请求的java和python实现方案

java 使用apache的包,当时找了挺久轮子,最后在外网看到. Basic Auth with Raw HTTP Headers Preemptive Basic Authentication basically means pre-sending the Authorization header. So – instead of going through the rather compl...

weixin_30456039的博客 441
上一篇: Virtual Destructor
下一篇: 数据结构与算法分析:第一章:Finding the kth largest number and The four basic rules of recursion
bigsnowstorm
博客等级 码龄17年 6粉丝 49原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值