在函数之间建立多个持久HTTP连接

时间:2018-03-26 22:05:16

标签: python python-3.x function python-requests

我想在两个不同的帐户上登录并创建两个独立的持久HTTP连接。我知道如何做到这一点的唯一方法是两次单独的登录功能,但这似乎是多余的,所以我只是使函数login()。但是现在我想以某种方式重复使用相同的登录功能在我的其他函数中创建多个持久性HTTP会话,但它超出了范围。

def login(username, password):
    requests.post('example.com', data=payload)

def website1():
    login("matthew", "qwerty")
    session = requests.session()

def website2():
    login("matthew2", "qwerty2")
    session = requests.session()

1 个答案:

答案 0 :(得分:2)

您可以使用支持多个域的请求cookie jar:

public class ApplicationDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<RoleClaim>(builder =>
        {
            builder.HasOne(roleClaim => roleClaim.Role).WithMany(role => role.Claims).HasForeignKey(roleClaim => roleClaim.RoleId);
            builder.ToTable("RoleClaim");
        });
        modelBuilder.Entity<Role>(builder =>
        {
            builder.ToTable("Role");
        });
        modelBuilder.Entity<UserClaim>(builder =>
        {
            builder.HasOne(userClaim => userClaim.User).WithMany(user => user.Claims).HasForeignKey(userClaim => userClaim.UserId);
            builder.ToTable("UserClaim");
        });
        modelBuilder.Entity<UserLogin>(builder =>
        {
            builder.HasOne(userLogin => userLogin.User).WithMany(user => user.Logins).HasForeignKey(userLogin => userLogin.UserId);
            builder.ToTable("UserLogin");
        });
        modelBuilder.Entity<User>(builder =>
        {
            builder.ToTable("User");
        });
        modelBuilder.Entity<UserRole>(builder =>
        {
            builder.HasOne(userRole => userRole.Role).WithMany(role => role.Users).HasForeignKey(userRole => userRole.RoleId);
            builder.HasOne(userRole => userRole.User).WithMany(user => user.Roles).HasForeignKey(userRole => userRole.UserId);
            builder.ToTable("UserRole");
        });
        modelBuilder.Entity<UserToken>(builder =>
        {
            builder.HasOne(userToken => userToken.User).WithMany(user => user.UserTokens).HasForeignKey(userToken => userToken.UserId);
            builder.ToTable("UserToken");
        });
    }
}

然后在两个网站上使用会话cookie:

jar = requests.cookies.RequestsCookieJar()

def login(url, domain, username, password):
    r = requests.post(url, data=payload)
    jar.set('session', r.cookies['session'], domain=domain) # assuming its name is session

了解更多信息: