Zum Hauptinhalt springen
LIVE
CVSS 6.9CVE-2026-69697 | Faveo Helpdesk (Community) through 2.0.3 and 2.0.4.RC.1 contains a server-side request forgery vulnerability in ApiExceptAuthController::checkUrl(), reachable through the unauthenticated and unthrottled GET /api/v1/helpdesk/url route, which validates the url parameter only as a well-formed URL, appends the fixed path api/v1/helpdesk/check-url and fetches it with curl with TLS certificate verification disabled and no restriction on the target host, port or addCVSS 6.3CVE-2026-69696 | Handesk through 1.5 contains a missing authentication vulnerability in the POST /webhook/bitbucket route, which is excluded from CSRF verification and processed by WebhookController::store() without validating any secret, signature, or request source before writing to the database. Unauthenticated attackers can send crafted Bitbucket issue payloads referencing a linked roadmap Idea or ticket to alter the Idea's status or inject attacker-controlled notes attriCVSS 8.7CVE-2026-69695 | Handesk through 1.5 contains an unrestricted file upload vulnerability in Attachment::storeAttachmentFromRequest() that allows authenticated agents to upload files with arbitrary extensions by attaching them to ticket comments without extension, MIME type, or size validation. Attackers can upload a PHP file via POST /tickets/{ticket}/comments, which is stored under storage/app/public/attachments and served from /storage/attachments/, to achieve remote code exCVSS 10.0CVE-2026-136823 | A vulnerability was found in D-Link R32 1.10B02. This affects an unknown function of the file /usr/bin/httpd of the component flupl self Endpoint. Performing a manipulation of the argument fpath results in os command injection. The attack can be initiated remotely. The exploit has been made public and could be used.CVSS 7.2CVE-2026-123879 | In authd before 0.7.2, an improper access control vulnerability allows an authenticated remote attacker to complete a first-time SSH login with another account's UID and incorrect primary GID, and to read or modify files owned by that account. This allows an attacker to access another account's data, potentially enabling account takeover or privilege escalation.CVSS 7.1CVE-2026-67209 | metasfresh through 5.175 contains a SQL injection vulnerability in the stressTest_massCacheInvalidation handler of DebugRestController, which concatenates the caller-supplied tableName request parameter into SELECT statements without parameterization or validation and only checks that the caller is authenticated. Authenticated WebUI users with any role can send GET requests to /rest/api/debug/stressTest/massCacheInvalidation with SQL in the tableName parameteCVSS 8.8CVE-2026-131817 | ChargePoint Home Flex wpa_passphrase Command Injection Remote Code Execution Vulnerability. This vulnerability allows network-adjacent attackers to execute arbitrary code on affected installations of ChargePoint Home Flex EV chargers. Authentication is not required to exploit this vulnerability. The specific flaw exists within the PSK parameter passed to the wpa_passphrase endpoint. The issue results from the lack of proper validation of a user-supplied strCVSS 9.4CVE-2026-136822 | A vulnerability has been found in D-Link R32 1.10B02. The impacted element is the function SetDeviceSettings of the file /usr/bin/httpd of the component DHMAPI Action Handler. Such manipulation of the argument TZLocation leads to os command injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used.
Alle im Drawer
Intelligence View
⚡ tsecurity.de Intelligence

Python for Beginners — Part 7: Modules, Errors & Files

Part 7 of a beginner-friendly series on learning Python from scratch. In Part 6, we learned to write reusable functions. Now it's time to make those functions…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 7 Min. Lesezeit
Quelle: dev.to
Rubrik: Secure Programming

Part 7 of a beginner-friendly series on learning Python from scratch.



In Part 6, we learned to write reusable functions. Now it's time to make those functions work in the real world: reading data from files, handling things when they go wrong, and using code other people have written.



This is where Python transitions from "learning exercises" to "actual programs." Real programs read files, talk to the internet, handle unexpected input, and use libraries to solve complex problems.






Modules and Imports



A module is a file containing Python code that you can reuse. Python comes with a huge standard library of modules, and you can also install external ones.






Using the math module






import math

print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.pi) # 3.14159...
print(math.ceil(4.3)) # 5 (round up)
print(math.floor(4.7)) # 4 (round down)






import math loads the math module. You access its functions and constants with dot notation: math.sqrt(), math.pi, etc.






Importing specific items



If you only need a few things, import them directly:




from math import sqrt, pi

print(sqrt(16)) # 4.0 (no need for math.)
print(pi) # 3.14159...






Now you use sqrt() directly, not math.sqrt().






Aliasing imports



Use as to give a module a shorter name:




import math as m

print(m.sqrt(16)) # 4.0






Or alias specific items:




from math import sqrt as square_root

print(square_root(16)) # 4.0









Working with datetime



The datetime module is essential for handling dates and times:




from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(now) # 2024-06-23 14:30:45.123456

# Create a specific date
birthday = datetime(1999, 5, 15)
print(birthday) # 1999-05-15 00:00:00

# Format as string
print(now.strftime("%Y-%m-%d")) # 2024-06-23
print(now.strftime("%A, %B %d")) # Sunday, June 23

# Time differences
future = now + timedelta(days=30)
print(future) # Date 30 days from now









Working with JSON



JSON (JavaScript Object Notation) is a standard format for exchanging data. Python dictionaries map perfectly to JSON:




import json

# Convert Python dict to JSON string
person = {
"name": "Ramesh",
"age": 25,
"city": "Chennai",
"hobbies": ["reading", "coding", "gaming"]
}

json_string = json.dumps(person)
print(json_string)
# {"name": "Ramesh", "age": 25, "city": "Chennai", "hobbies": ["reading", "coding", "gaming"]}

# Convert JSON string back to Python dict
parsed = json.loads(json_string)
print(parsed["name"]) # Ramesh






Reading and writing JSON files:




import json

# Write to file
data = {"name": "Ramesh", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)

# Read from file
with open("data.json", "r") as file:
data = json.load(file)
print(data)









Regular Expressions (Regex)



Regex is a language for pattern matching in text. It's powerful but takes time to master. Here are common patterns:




import re

text = "My phone is 555-1234 and email is [email protected]"

# Find a pattern
phone = re.search(r"\d{3}-\d{4}", text)
if phone:
print(phone.group()) # 555-1234

# Find all matches
emails = re.findall(r"[\w.-]+@[\w.-]+\.\w+", text)
print(emails) # ['[email protected]']

# Replace
cleaned = re.sub(r"\d", "X", text)
print(cleaned) # Phone is XXX-XXXX...

# Check if pattern matches
if re.match(r"^\d+$", "12345"):
print("It's all digits")






Regex patterns (a few common ones):





  • \d — any digit (0-9)


  • \w — any word character (letter, digit, underscore)


  • \s — any whitespace


  • . — any character


  • * — zero or more


  • + — one or more


  • ? — zero or one


  • {n} — exactly n times


  • ^ — start of string


  • $ — end of string


  • [abc] — a, b, or c



Regex is complex; this is just an introduction. Most beginners use regex sparingly and look up patterns when needed.






File Input and Output






Reading files






# Simple read
with open("myfile.txt", "r") as file:
content = file.read()
print(content)

# Read line by line
with open("myfile.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline

# Read all lines as a list
with open("myfile.txt", "r") as file:
lines = file.readlines()
print(lines[0]) # First line






The with statement is crucial — it automatically closes the file when you're done, even if an error occurs.






Writing files






# Write (overwrites if file exists)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Second line\n")

# Append (add to end of file)
with open("output.txt", "a") as file:
file.write("Third line\n")









Working with file paths






import os

# Check if file exists
if os.path.exists("myfile.txt"):
print("File found")

# Get file size
size = os.path.getsize("myfile.txt")
print(f"File size: {size} bytes")

# List files in directory
files = os.listdir(".")
print(files)

# Create directory
os.makedirs("my_folder", exist_ok=True)

# Delete file
os.remove("myfile.txt")









Exception Handling



Real programs fail sometimes — bad file paths, network errors, invalid input. Handle these gracefully with try/except:




try:
# Code that might fail
number = int("not a number")
except ValueError:
print("That's not a valid number")






If int() fails, Python catches the ValueError and runs the except block instead of crashing.






Multiple exceptions






try:
file = open("missing.txt", "r")
number = int(file.read())
except FileNotFoundError:
print("File doesn't exist")
except ValueError:
print("File contains non-numeric data")
except Exception as e:
print(f"Something went wrong: {e}")






Handle specific errors first, then generic ones. Exception catches everything.






Try, except, else, finally






try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found")
else:
# Runs if no exception occurred
print(f"Successfully read {len(data)} characters")
finally:
# Always runs, useful for cleanup
print("Done")








  • try — code that might fail


  • except — what to do if it fails


  • else — what to do if it succeeds


  • finally — always runs (cleanup)






Raising exceptions



You can raise exceptions yourself:




def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return True

try:
validate_age(-5)
except ValueError as e:
print(f"Invalid input: {e}")









Installing External Libraries with pip



The pip package manager lets you install libraries others have written:




pip install requests      # Install the requests library
pip install numpy pandas # Install multiple packages
pip install requests==2.28.0 # Install specific version
pip list # Show installed packages
pip uninstall requests # Remove a package






Once installed, use them like built-in modules:




import requests

response = requests.get("https://api.github.com")
print(response.status_code) # 200






Popular libraries for beginners:





  • requests — make web requests


  • numpy — numerical computing


  • pandas — data analysis


  • matplotlib — plotting and visualization


  • flask — build web applications






Practical Examples






Example 1: Read and count words






def count_words(filename):
try:
with open(filename, "r") as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
print(f"Error: {filename} not found")
return 0

count = count_words("myfile.txt")
print(f"Total words: {count}")









Example 2: Save and load JSON data






import json

def save_contacts(contacts, filename):
with open(filename, "w") as file:
json.dump(contacts, file, indent=2)

def load_contacts(filename):
try:
with open(filename, "r") as file:
return json.load(file)
except FileNotFoundError:
return []

# Save
contacts = [
{"name": "Ramesh", "phone": "555-1234"},
{"name": "Priya", "phone": "555-5678"}
]
save_contacts(contacts, "contacts.json")

# Load
loaded = load_contacts("contacts.json")
print(loaded)









Example 3: Extract data with regex






import re

def extract_emails(text):
pattern = r"[\w.-]+@[\w.-]+\.\w+"
return re.findall(pattern, text)

text = "Contact me at [email protected] or [email protected]"
emails = extract_emails(text)
print(emails) # ['[email protected]', '[email protected]']









Why This Matters



File I/O and exception handling are what separate learning exercises from real programs. Every professional program reads data from files or the internet, handles errors gracefully, and uses external libraries. Modules let you leverage thousands of hours of other people's work instead of writing everything yourself.



The most common beginner mistakes:




  • Forgetting to close files (use with — it's mandatory style)

  • Not handling file not found errors

  • Assuming regex patterns are simpler than they are

  • Catching generic Exception instead of specific errors

  • Not installing libraries with pip correctly






What's Next



In Part 8, the final part, we'll explore object-oriented programming — classes, inheritance, and polymorphism. OOP is how professional Python code is structured, and everything you've learned so far will come together.






This is Part 7 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, Part 4: Operators & Control Flow, Part 5: Collections, and Part 6: Functions.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Community discussion & comments

🌐 Join the main chat

Start the discussion in the Social Chat broadcast stream or submit an expert contribution via the supplement form above.

Community Rating &amp; Social Proof
⭐ Reader Rating
–
Ø / 5.0
No reader ratings yet
Was this article helpful?
0
Submit your rating
Detailed rating (optional)
Content & Quality
Source & Credibility
Freshness
Security Briefing Free · 1-Click Unsubscribe

Intelligence Digest — free

The top security news daily · unsubscribe anytime

Related story clusters & sources (vector AI)

6 Cluster
18 sources
Samsung’s Galaxy Buds 4 Pro Just Hit a Record-Low Black Friday Price on Amazon
CNET 38 min. ago
17 more sources
Engadget1 hour agoWe reviewed these 10 gadgets, and they're now on sale for Black Friday WinFuture News1 hour agoBlack-Friday-Woche: Bei Amazon läuft die Schnäppchenjagd 26. November Latest from TechRadar1 hour agoI’m an avid cyclist and these Black Friday tech deals on Amazon are zooming straight to my cart — save up to 50% off smartwatches, headphones, action cameras and more CNET1 hour agoBlack Friday Is Here and You Can Grab a New Dyson Vacuum for Up to a Massive $330 Off CNET2 hours agoStop Scrambling for an Outlet and Snag This 200-Watt Power Bank Instead While It’s $50 Off for Black Friday Latest from TechRadar2 hours agoTake our Black Friday deal quiz and find your perfect Dyson cordless vacuum CNET9 days agoSave Even More On Black Friday With Exclusive 10% Off StackSocial Promo Code for CNET Readers CNET3 hours agoThis Black Friday Deal Knocks $120 Off My Daily Driver Sonos Ace Headphones CNET28 days agoWe Found 67 Walmart Black Friday Deals You Can Shop Now, With Prices Starting at Only $4 CNET3 hours agoThe Disney Plus and Hulu Bundle Plummets to $5 a Month for Black Friday Latest from TechRadar3 hours agoRefurbished iPhone sales are on the rise — here's why buying pre-owned is a great idea this Black Friday Macerkopf.de4 hours agoApple Watch 12, SE 3 und Ultra 3: Amazon reduziert alle drei Modelle zum Black Friday Latest from TechRadar4 hours agoThe Lenovo Legion Tower 5i is the streaming and editing PC I'd pick — now $1,440 off at $2,230 for Black Friday CNET19 days agoSave Up to $700 on Eufy Robot Vacuums, Security Cameras and More This Black Friday CNET4 hours agoAmazon Just Knocked Up to 21% Off Ecobee’s Top-Rated Smart Thermostats for Black Friday CNET4 hours agoWe’re Counting Down CNET Readers’ Top Picks This Black Friday Google Chrome4 hours agoGoogle Chrome: Use Split View in Chrome to shop Black Friday finds for every side of your style. ✨
Similar posts
🔍 Verwandte News

Auch interessante Nachrichten Python for Beginners — Part 7: Modules, Errors & Files

Thematisch verwandte Begriffe: Python, Beginners, Part, Modules · 6 Treffer

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

💬 Loading comments…
Pull to refresh
Widgets & Topics
Loading widgets…
Nächster Beitrag