如何为变量赋值非字符串值?Python SSL位或赋值报错求助
Hey there! Let's break down why that error is popping up and get your code working smoothly.
Why the Error Happens
The core issue here is that you’re storing string versions of the SSL options in your list, not the actual integer constants the ssl module relies on.
When you write 'ssl.OP_NO_TLSv1_1', that’s just plain text—Python doesn’t recognize it as the actual option value. The context.options |= ... operation needs an integer (or ssl.Options type) to perform the bitwise OR, so passing a string triggers that TypeError.
How to Store & Use Real SSL Options
Instead of storing strings, you can directly save the ssl module’s constant values in your list or dictionary. Here are a few clean, readable approaches:
1. Store Constants Directly in a List
This keeps things simple while retaining readability:
import ssl # Store the actual SSL option constants, not their string names noTLS = [ ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv3, ssl.OP_NO_TLSv1, ssl.OP_NO_TLSv1_1 ] # Initialize your SSL context context = ssl.create_default_context() # Now this works perfectly! context.options |= noTLS[3]
2. Use a Dictionary for Named References
If you want to reference options by descriptive names (for even clearer code), use a dictionary to map names to the constants:
import ssl noTLS_map = { "disable_ssl_v2": ssl.OP_NO_SSLv2, "disable_ssl_v3": ssl.OP_NO_SSLv3, "disable_tls_v1": ssl.OP_NO_TLSv1, "disable_tls_v1_1": ssl.OP_NO_TLSv1_1 } context = ssl.create_default_context() # Reference by name for instant clarity context.options |= noTLS_map["disable_tls_v1_1"]
3. Enable Multiple Options at Once
If you want to disable several old protocols in one go, you can either combine them with bitwise ORs or loop through your list:
# Combine options directly in one line context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 # Or loop through your list to apply all options for option in noTLS: context.options |= option
Key Takeaway
The ssl.OP_* values are integer constants under the hood—storing them as strings strips away their actual functionality. By saving the constants themselves, you let Python use them correctly for bitwise operations with context.options.
内容的提问来源于stack exchange,提问作者user9371654

