Zum Hauptinhalt springen
LIVE
CVSS 8.7CVE-2026-137509 | Scriban before 7.6.0 contains a resource exhaustion vulnerability that allows template authors to bypass LimitToString by rendering a ScriptObject with many members. Attackers can supply a small template whose ScriptObject.ToString concatenates large member values without length tracking, allocating multi-gigabyte strings and causing memory exhaustion.CVSS 8.7CVE-2026-137510 | Scriban and Scriban.Signed before 7.6.0 allow template authors to bypass the LimitToString string length limit because the string.literal, string.base64_encode, html.escape, html.newline_to_br, html.url_encode, and html.url_escape builtins lack allocation guards. An attacker who can supply a small template can repeatedly call these builtins under the default TemplateContext to force multi-gigabyte allocations and exhaust host memory.CVSS 7.2CVE-2026-137511 | Scriban before 7.6.0 contains a state isolation vulnerability because TemplateContext.Reset() does not clear the Tags dictionary holding array.cycle and math.random state. Attackers supplying templates to a reused context can observe or influence cycle positions and random sequences across renders, and accumulate unbounded cycle entries to exhaust memory.CVSS 8.7CVE-2026-137512 | Scriban before 7.6.0 contains a resource exhaustion vulnerability that allows attackers to bypass LoopLimit by supplying large JSON input to object.from_json. Attackers can pass a flat JSON array or object with hundreds of thousands of elements, which JsonElementExtensions materializes without loop checks, exhausting CPU and memory.CVSS 8.7CVE-2026-137513 | justhtml before 3.17.0 contains a denial of service vulnerability in decode_entities_in_text that allows unauthenticated attackers to crash parsing via non-ASCII Unicode digits in numeric character references. Attackers can submit a payload like &#² in HTML text or attributes, causing an uncaught ValueError from int() that aborts JustHTML() and stream() parsing.CVSS 8.3CVE-2026-137514 | Nodemailer 9.1.0 before 10.4.1 lowercases recipient domains with JavaScript toLowerCase() in _normalizeAddress before UTS-46 mapping, which converts U+1E9E and word-final U+03A3 differently than WHATWG/UTS-46 validators. An unprivileged attacker can submit an address an application's allow-list approves, causing invites or shared links to reach an attacker-registered domain.CVSS 5.3CVE-2026-137515 | AzuraCast before 0.24.1 contains a missing authorization vulnerability in RelaysController::updateAction that allows any authenticated user to modify shared relays and delete other stations' relay associations. Attackers can POST a relay base_url to /internal/relays to rename the relay, wipe StationRemote rows of unmanaged stations, and spoof public now-playing data.CVSS 5.3CVE-2026-137516 | AzuraCast before 0.24.0 contains a missing authorization vulnerability in the StationPublicApi middleware that allows any authenticated user to access non-public stations without per-station permissions. Attackers can change the station_id path parameter to list and download on-demand media, read schedule data, and submit song requests to unauthorized stations.
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: Sichere Programmierung

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 user@example.com"

# 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) # ['user@example.com']

# 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 john@example.com or jane.doe@company.co.uk"
emails = extract_emails(text)
print(emails) # ['john@example.com', 'jane.doe@company.co.uk']









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.

Information ergänzen Fachhinweis, Update, Korrektur oder Quelle zur Meldung beitragen
Gäste-Hinweise werden kurz redaktionell geprüft und danach hier angezeigt.

Community-Hinweise zur Meldung

0 freigegeben
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:

💬 Topluluk tartışması ve yorumlar

🌐 Ana sohbete katıl

Tartışmayı başlat: Social Chat yayın akışı veya yukarıdaki ekleme formuyla uzman katkısı gönder.

Community Rating &amp; Social Proof
⭐ Okuyucu Puanı
–
Ø / 5.0
Hiçbir okuyucu henüz yorum yok
Bu makale yararlı mıydı?
0
Değerlendirmenizi gönderin
Detaylı değerlendirme (isteğe bağlı)
İçerik ve Kalite
Kaynak ve Güvenilirlik
Güncellik
Security Briefing Ücretsiz · Tek tıkla abonelikten çıkma

Zeka Digest - ücretsiz

Günlük en önemli güvenlik haberi · herhangi bir zamanda alınabilir

İlgili Story Cluster & Kaynaklar (vector AI)

1 Cluster
2 Kaynaklar
Privacy-Focused Personal PDF Answers — 4 Retrieval Gates for Relevance Tuning
DEV Community 31 dakika önce
1 başka bir kaynak
Benzer katkılar
🔍 Verwandte News

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

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

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Yorumlar yüklenir..
Update to Update
Widgets & Topics
Loading widgets…
Nächster Beitrag