WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Advanced · question 54 of 100

How do you ensure that your Python code is secure against common vulnerabilities, such as SQL injection and XSS?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

Python provides several built-in modules and third-party libraries that can help you secure your code against common vulnerabilities. Here are some techniques you can use:

Use parameterized queries instead of building SQL statements with user input. The sqlite3 module provides a way to do this, and third-party libraries like SQLAlchemy can also help.

    import sqlite3
    
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    
    username = input("Enter username: ")
    password = input("Enter password: ")
    
    # Using parameterized queries to prevent SQL injection
    c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))

Validate and sanitize user input before using it. Use libraries like html to escape HTML tags and json to validate JSON input.

    import json
    
    # Validating JSON input
    try:
        data = json.loads(request.data)
        except ValueError:
            return "Invalid JSON input", 400
    
    # Sanitizing user input to prevent XSS attacks
    from html import escape
    
    user_input = '<script>alert("Hello")</script>'
    sanitized_input = escape(user_input)

Use secure hash algorithms, like SHA-256 or SHA-512, to store passwords. The hashlib module can help you generate and verify secure password hashes.

    import hashlib
    
    password = 'password123'
    salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
    hashed_password = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
    hashed_password = binascii.hexlify(hashed_password)

Use HTTPS instead of HTTP to encrypt data in transit. Use libraries like requests to make HTTPS requests and ssl to configure SSL/TLS connections.

    import requests
    
    response = requests.get('https://example.com')

Avoid using eval() and exec() functions, as they can execute arbitrary code and introduce security vulnerabilities. If you need to evaluate user input, use safer alternatives like ast.literal_eval().

    import ast
    
    user_input = '[1, 2, 3]'
    try:
        data = ast.literal_eval(user_input)
    except ValueError:
        return "Invalid input", 400
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics