-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfiguration-file.html
More file actions
744 lines (655 loc) · 50.2 KB
/
configuration-file.html
File metadata and controls
744 lines (655 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Python configuration file</title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<link href="assets/img/Favicon-1.png" rel="icon">
<link href="assets/img/Favicon-1.png" rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="assets/vendor/aos/aos.css" rel="stylesheet">
<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
<link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
<link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet">
<!-- Creating a python code section-->
<link rel="stylesheet" href="assets/css/prism.css">
<script src="assets/js/prism.js"></script>
<!-- Template Main CSS File -->
<link href="assets/css/style.css" rel="stylesheet">
<!-- To set the icon, visit https://fontawesome.com/account-->
<script src="https://kit.fontawesome.com/5d25c1efd3.js" crossorigin="anonymous"></script>
<!-- end of icon-->
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<!-- Include the highlight.js library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/default.min.css">
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/highlight.min.js"></script> -->
<!-- =======================================================
* Template Name: iPortfolio
* Updated: Sep 18 2023 with Bootstrap v5.3.2
* Template URL: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>
<body>
<!-- ======= Mobile nav toggle button ======= -->
<i class="bi bi-list mobile-nav-toggle d-xl-none"></i>
<!-- ======= Header ======= -->
<header id="header">
<div class="d-flex flex-column">
<div class="profile">
<img src="assets/img/myphoto.jpeg" alt="" class="img-fluid rounded-circle">
<h1 class="text-light"><a href="index.html">Arun</a></h1>
<div class="social-links mt-3 text-center">
<a href="https://www.linkedin.com/in/arunp77/" target="_blank" class="linkedin"><i class="bx bxl-linkedin"></i></a>
<a href="https://github.com/arunp77" target="_blank" class="github"><i class="bx bxl-github"></i></a>
<a href="https://twitter.com/arunp77_" target="_blank" class="twitter"><i class="bx bxl-twitter"></i></a>
<a href="https://www.instagram.com/arunp77/" target="_blank" class="instagram"><i class="bx bxl-instagram"></i></a>
<a href="https://arunp77.medium.com/" target="_blank" class="medium"><i class="bx bxl-medium"></i></a>
</div>
</div>
<nav id="navbar" class="nav-menu navbar">
<ul>
<li><a href="index.html#hero" class="nav-link scrollto active"><i class="bx bx-home"></i> <span>Home</span></a></li>
<li><a href="index.html#about" class="nav-link scrollto"><i class="bx bx-user"></i> <span>About</span></a></li>
<li><a href="index.html#resume" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>Resume</span></a></li>
<li><a href="index.html#portfolio" class="nav-link scrollto"><i class="bx bx-book-content"></i> <span>Portfolio</span></a></li>
<li><a href="index.html#skills-and-tools" class="nav-link scrollto"><i class="bx bx-wrench"></i> <span>Skills and Tools</span></a></li>
<li><a href="index.html#language" class="nav-link scrollto"><i class="bi bi-menu-up"></i> <span>Languages</span></a></li>
<li><a href="index.html#awards" class="nav-link scrollto"><i class="bi bi-award-fill"></i> <span>Awards</span></a></li>
<li><a href="index.html#professionalcourses" class="nav-link scrollto"><i class="bx bx-book-alt"></i> <span>Professional Certification</span></a></li>
<li><a href="index.html#publications" class="nav-link scrollto"><i class="bx bx-news"></i> <span>Publications</span></a></li>
<!-- <li><a href="index.html#extra-curricular" class="nav-link scrollto"><i class="bx bx-rocket"></i> <span>Extra-Curricular Activities</span></a></li> -->
<!-- <li><a href="#contact" class="nav-link scrollto"><i class="bx bx-envelope"></i> <span>Contact</span></a></li> -->
</ul>
</nav><!-- .nav-menu -->
</div>
</header><!-- End Header -->
<main id="main">
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Data Engineering</h2>
<ol>
<li><a href="Data-engineering.html" class="clickable-box">Content section</a></li>
<li><a href="index.html#portfolio" class="clickable-box">Portfolio section</a></li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<!------ right dropdown menu ------->
<div class="right-side-list">
<div class="dropdown">
<button class="dropbtn"><strong>Shortcuts:</strong></button>
<div class="dropdown-content">
<ul>
<li><a href="cloud-compute.html"><i class="fas fa-cloud"></i> Cloud</a></li>
<li><a href="AWS-GCP.html"><i class="fas fa-cloud"></i> AWS-GCP</a></li>
<li><a href="amazon-s3.html"><i class="fas fa-cloud"></i> AWS S3</a></li>
<li><a href="ec2-confi.html"><i class="fas fa-server"></i> EC2</a></li>
<li><a href="Docker-Container.html"><i class="fab fa-docker" style="color: rgb(29, 27, 27);"></i> Docker</a></li>
<li><a href="Jupyter-nifi.html"><i class="fab fa-python" style="color: rgb(34, 32, 32);"></i> Jupyter-nifi</a></li>
<li><a href="snowflake-task-stream.html"><i class="fas fa-snowflake"></i> Snowflake</a></li>
<li><a href="data-model.html"><i class="fas fa-database"></i> Data modeling</a></li>
<li><a href="sql-basics.html"><i class="fas fa-table"></i> SQL</a></li>
<li><a href="sql-basic-details.html"><i class="fas fa-database"></i> SQL</a></li>
<li><a href="Bigquerry-sql.html"><i class="fas fa-database"></i> Bigquery</a></li>
<li><a href="scd.html"><i class="fas fa-archive"></i> SCD</a></li>
<li><a href="sql-project.html"><i class="fas fa-database"></i> SQL project</a></li>
<!-- Add more subsections as needed -->
</ul>
</div>
</div>
</div>
<!-- ======= Portfolio Details Section ======= -->
<section id="portfolio-details" class="portfolio-details">
<div class="container">
<div class="row gy-4">
<h1>Importance of Configuration Files in Python : A Focus on ETL Pipelines</h1>
<div class="col-lg-8">
<div class="portfolio-details-slider swiper">
<div class="swiper-wrapper align-items-center">
<figure>
<img src="assets/img/data-engineering/python-configuration.png" alt="" style="max-width: 80%; max-height: auto;">
<figcaption style="text-align: center;"><b></b> <a href="" target="_blank"></a> </figcaption>
</figure>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
<div class="col-lg-4 grey-box">
<h3>Content</h3>
<ol>
<li><a href="#introduction">Introduction</a>
<ul>
<li><a href="#fundamental">Fundamentals of Oceanography</a></li>
<li><a href="#remote-key">Key Remote Sensing Instruments</a></li>
</ul>
</li>
<li><a href="#Sentinel-3">Sentinel 3 : Satellite</a>
<ul>
<li><a href="#instruments">Sentinel-3 Instruments</a></li>
<li><a href="#what-conf">What Are Configuration Files?</a></li>
<li><a href="#why-conf">Why Use Configuration Files?</a></li>
<li><a href="#how-conf">How to Use Configuration Files in ETL Projects?</a></li>
<li>
<ul>
<li><a href="#data-sentinel3">Accessing OLCI data via the EUMETSAT Data Store</a></li>
<!-- <li><a href=""></a></li>
<li><a href=""></a></li> -->
</ul>
</li>
<li><a href="#olci-product">OLCI Product</a></li>
</ul>
</li>
<li><a href="#reference">Reference</a></li>
</ol>
</div>
</div>
<!---------sections start here ------------>
<hr>
<section>
<div class="alert alert-success"> <i class="bi bi-arrow-right-circle"></i>
This is one of the most important concepts in python project development. I have taken few part of the page from <a href="https://hackersandslackers.com/simplify-your-python-projects-configuration/" target="_blank">reference</a>.
</div>
<!----------------->
<h1 id="introduction">Introduction</h1>
When building complex Python projects like ETL (Extract, Transform, Load) pipelines, managing configurations effectively becomes crucial. Configuration files are an essential tool in this process, providing a centralized way to manage settings, improve maintainability, and enhance flexibility. Let's dive into what configuration files are, how they are helpful, and how to use them in your ETL projects.
<h3 id="what-conf">What Are Configuration Files?</h3>
Configuration files store settings and parameters that a program needs to run. Instead of hardcoding values into your code, which can lead to maintenance challenges and inflexibility, configuration files allow you to separate configuration from code. These files can be in various formats, including JSON, YAML, INI, and environment variables.
<ul>
<li><b>JSON:</b> Easy to read and widely used, especially in web applications.</li>
<li><b>YAML (Yet Another Markup Language):</b> More human-readable than JSON, often used in DevOps and configuration management.</li>
<li><b>INI:</b> Simple format for key-value pairs, commonly used in older applications.</li>
<li><b>TOML:</b> Configure from .toml. TOML files define variables via key/value pairs in a similar manner to that of ini files. Unlike ini files, however, TOML expects that the values of keys to be stored as the data type they're intended to be utilized as.</li>
<li><b>Environment Variables:</b> Managed by the operating system, suitable for sensitive information (for more details, check out my blog post on <a href="https://medium.com/@arunp77/best-python-programming-habits-for-complex-projects-9a46b73dcb38" target="_blank">best habits of Python programming</a> <a href="" target="_blank">enviroment variable</a> ).</li>
</ul>
<h3 id="why-conf">Why Use Configuration Files?</h3>
<ol>
<li><b>Centralized Management:</b> Configuration files allow you to manage settings in one place, making it easier to update and maintain.</li>
<li><b>Flexibility:</b> You can change configurations without modifying the codebase, facilitating easier adjustments across different environments (development, testing, production).</li>
<li><b>Security:</b> Sensitive information, like database credentials and API keys, can be managed securely using environment variables or encrypted configuration files.</li>
<li><b>Scalability:</b> As projects grow, configuration files help in managing complexity by organizing settings logically.</li>
<li><b>Portability:</b> Configuration files make it easier to share and deploy your code across different environments and systems.</li>
</ol>
<h3 id="how-conf">How to Use json-Configuration Files in ETL Projects?</h3>
Let's consider an example ETL pipeline where we need to extract data from a source, transform it, and load it into a destination. We'll use a JSON configuration file to manage our settings.
<ol>
<li><b>Step 1: Define the Configuration File: </b>Create a <code>config.json</code> file with necessary settings, such as source and destination details, transformation rules, and logging configurations.
<pre class="language-python"><code>
# Json-configuration file
{
"source": {
"type": "database",
"host": "localhost",
"port": 5432,
"database": "source_db",
"user": "source_user",
"password": "source_password"
},
"destination": {
"type": "database",
"host": "localhost",
"port": 5432,
"database": "destination_db",
"user": "dest_user",
"password": "dest_password"
},
"transformations": [
{"name": "remove_nulls", "fields": ["field1", "field2"]},
{"name": "convert_types", "fields": {"field3": "int", "field4": "float"}}
],
"logging": {
"level": "INFO",
"file": "etl.log"
}
}
</code></pre>
</li>
<li><b>Step 2: Load the Configuration File in Python: </b>In the ETL script, load the configuration file to access the settings.
<pre class="language-python"><code>
# Main python script
import json
def load_config(config_file):
with open(config_file, 'r') as file:
config = json.load(file)
return config
config = load_config('config.json')
</code></pre>
</li>
<li><b>Step 3: Use Configurations in ETL Pipeline: </b>Utilize the loaded configurations in your ETL process.
<pre class="language-python"><code>
# Main python script
import logging
import psycopg2
# Function to set up logging
def setup_logging(log_config):
logging.basicConfig(filename=log_config['file'], level=log_config['level'])
logging.info("Logging is set up.")
# Function to extract data from the source
def extract_data(source_config):
connection = psycopg2.connect(
host=source_config['host'],
port=source_config['port'],
database=source_config['database'],
user=source_config['user'],
password=source_config['password']
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM source_table")
data = cursor.fetchall()
connection.close()
return data
# Function to transform the data
def transform_data(data, transformations):
for transformation in transformations:
if transformation['name'] == 'remove_nulls':
data = [row for row in data if None not in row]
elif transformation['name'] == 'convert_types':
for row in data:
for field, dtype in transformation['fields'].items():
if dtype == 'int':
row[field] = int(row[field])
elif dtype == 'float':
row[field] = float(row[field])
return data
# Function to load data into the destination
def load_data(destination_config, data):
connection = psycopg2.connect(
host=destination_config['host'],
port=destination_config['port'],
database=destination_config['database'],
user=destination_config['user'],
password=destination_config['password']
)
cursor = connection.cursor()
for row in data:
cursor.execute("INSERT INTO destination_table VALUES (%s, %s, %s, %s, %s)", row)
connection.commit()
connection.close()
# Main function to run the ETL pipeline
def main():
config = load_config('config.json')
setup_logging(config['logging'])
logging.info("Starting ETL process.")
data = extract_data(config['source'])
transformed_data = transform_data(data, config['transformations'])
load_data(config['destination'], transformed_data)
logging.info("ETL process completed.")
if __name__ == '__main__':
main()
</code></pre>
</li>
<li><b>Step 4: Managing Sensitive Information: </b>For sensitive information like passwords, consider using environment variables or secret management tools.
<pre class="language-python"><code>
# Example with Environment Variables:
import os
source_password = os.getenv('SOURCE_PASSWORD')
destination_password = os.getenv('DEST_PASSWORD')
# Use these variables in the connection setup
source_config['password'] = source_password
destination_config['password'] = destination_password
</code></pre>
<div class="grey-box"><strong>Note: </strong> If we need to update the main function, then we can do it as follows:
<pre class="language-python"><code>
def main():
config = load_config('config.json')
# Overwrite passwords with environment variables
config['source']['password'] = os.getenv('SOURCE_PASSWORD', config['source']['password'])
config['destination']['password'] = os.getenv('DEST_PASSWORD', config['destination']['password'])
setup_logging(config['logging'])
logging.info("Starting ETL process.")
data = extract_data(config['source'])
transformed_data = transform_data(data, config['transformations'])
load_data(config['destination'], transformed_data)
logging.info("ETL process completed.")
</code></pre>
</div>
</li>
<li><b>Conclusion: </b> Configuration files are invaluable in managing complex Python projects, especially ETL pipelines. They provide a centralized, flexible, and secure way to handle settings, making your codebase cleaner and easier to maintain. By separating configuration from code, you enhance the scalability and portability of your projects, ensuring they can adapt to various environments and requirements with minimal effort.</li>
</ol>
<h3 id="how-confi-env">Setting configuration using the enviroment variables</h3>
In the world of data engineering and machine learning, maintaining clean and secure code is paramount. One key practice that enhances both security and efficiency is the use of enviroment
variables in a file <code>.env</code> in the project directory. The <code>.env</code> file is a simple text file used to store environment variables. These variables can include sensitive
information like API keys, database credentials, and configuration settings.
<ul>
<li><strong>Security:</strong> Storing sensitive data in `.env` files keeps it out of your main codebase, reducing the risk of exposing secrets when sharing or uploading your code to platforms like GitHub.</li>
<li><strong>Configuration Management:</strong> `.env` files allow for easy management of different configurations for development, testing, and production environments. This makes your code more adaptable and easier to maintain.</li>
<li><strong>Simplicity:</strong> Loading environment variables from a `.env` file is straightforward, using libraries like python-`dotenv` in Python.</li>
</ul>
<h5 id="loading-env">Loading the <code>.env</code> file</h5>
Create `.env` in the root directory of the project and save the environment variables, such as database URLs, API keys, and secret keys, which are sensitive information that you don't want to expose in your code. For example:
<pre class="language-python"><code>
DATABASE_URL=your_database_url
API_KEY=your_api_key
SECRET_KEY=your_secret_key
</code></pre>
To avoid sharing your secrets, add `.env` to the `gitignore` file. Adding .env to .gitignore protects your sensitive information from being exposed publicly or shared unintentionally. To load the enviroment variables in the python scripts, Use
<pre class="language-python"><code>
from dotenv import load_dotenv
import os
load_dotenv()
database_url = os.getenv("DATABASE_URL")
api_key = os.getenv("API_KEY")
secret_key = os.getenv("SECRET_KEY")
</code></pre>
where:
<ul>
<li><code>load_dotenv()</code> loads the environment variables from the .env </li>
<li><code>os.getenv()</code> retrieves the value of the specified environment variable.</li>
</ul>
<h3 id="conf-ini">Configure from .ini</h3>
ini files are perhaps the most straight configuration files available to us. <code>ini</code> files are highly suitable for smaller projects, mostly because these files only support hierarchies 1-level deep. <code>ini</code> files are essentially flat files, with the exception that variables can belong to groups. The below example demonstrates how variables sharing a common theme may fall under a common title, such as <code>[DATABASE]</code> or <code>[LOGS]</code> (the config.ini is):
<pre class="language-python"><code>
[APP]
ENVIRONMENT = development
DEBUG = False
[DATABASE]
USERNAME = root
PASSWORD = p@ssw0rd
HOST = 127.0.0.1
PORT = 5432
DB = my_database
[LOGS]
ERRORS = logs/errors.log
INFO = data/info.log
[FILES]
STATIC_FOLDER = static
TEMPLATES_FOLDER = templates
</code></pre>
This structure surely makes things easier to understand by humans, but the practicality of this structure goes beyond aesthetics. Let's parse this file with Python's
<a href="os-module.html">configparser</a> library to see what's really happening. We get started by saving the contents of <code>config.ini</code> to a variable called config in a python script ():
<pre class="language-python"><code>
"""Load configuration from .ini file."""
import configparser
# Read local file `config.ini`.
config = configparser.ConfigParser()
config.read('settings/config.ini') # suppose our config.ini is in 'setting' folder of home directory.
</code></pre>
Calling <code>read()</code> on an <code>ini</code> file does much more than store plain data; our config variable is now a unique data structure, allowing us various methods for reading and writing values to our config. Try running print(config) to see for yourself: <code>< configparser.ConfigParser object at 0x10e58c390 ></code>. Now using <code>config</code> variable, we can get various values from the <code>config.ini</code> (here we use <code>get()</code> method, where it returns the value as a string) as:
<pre class="language-python"><code>
# Get values from our .ini file
config.get('DATABASE', 'HOST') # retrieves the value associated with the 'HOST' key from the 'DATABASE'
config['DATABASE']['HOST'] # alternative way to access the same value.
config.getboolean('APP', 'DEBUG') # retrieves the value associated with the 'DEBUG' key from the 'APP'
# section and converts it to a boolean.
</code></pre>
The main difference is between the first and second is that if the key doesn't exist, this method will raise a <code>KeyError</code> instead of a <code>configparser.NoOptionError</code>. This method retrieves the value associated with the 'DEBUG' key from the 'APP' section and converts it to a boolean.
<h3 id="yaml">Configuring Applications from .yaml Files</h3>
YAML is a human-readable data serialization standard that can be used in conjunction with all programming languages and is often used to write configuration files. Its syntax is minimal and straightforward, which makes it easier for humans to read and write compared to JSON or XML.
<ol>
<li><strong>Why Use YAML for Configuration?</strong>
<ul>
<li><b>Readability:</b> YAML’s syntax is clean and easy to understand.</li>
<li><b>Hierarchical Data:</b> It naturally represents hierarchical data, making it suitable for complex configurations.</li>
<li><b>Language-agnostic:</b> YAML can be used with any programming language, making it versatile.</li>
</ul>
</li>
<li><strong>Basic Structure of a .yaml File: </strong></li>
<pre class="language-python"><code>
database:
host: localhost
port: 5432
user: admin
password: secret
features:
enable_feature_x: true
max_connections: 100
</code></pre>
<li><strong>Configuring Applications with YAML: </strong>Let’s walk through configuring an application using a YAML file. We’ll use a Python application as an example. </li>
<ul>
<li><b>Step-1: Create a YAML Configuration File: </b>First, create a file named <code>config.yaml</code>:
<pre class="language-python"><code>
app:
name: MyApp
version: 1.0
database:
host: localhost
port: 5432
user: admin
password: secret
logging:
level: INFO
file: /var/log/myapp.log
</code></pre>
<li><b>Step 2: Load the YAML Configuration in Your Application: </b>To read and use this configuration in your application, you’ll need a YAML parser. In Python, <code>PyYAML</code> is a popular library for this purpose. Next, load the configuration file in your Python application:</li>
<pre class="language-python"><code>
import yaml
def load_config(file_path):
with open(file_path, 'r') as file:
config = yaml.safe_load(file)
return config
config = load_config('config.yaml')
# Accessing configuration values
app_name = config['app']['name']
db_host = config['database']['host']
log_level = config['logging']['level']
print(f"App Name: {app_name}")
print(f"Database Host: {db_host}")
print(f"Log Level: {log_level}")
</code></pre>
<li><b>Step 3: Using the Configuration: </b>With the configuration loaded, you can now use it to set up your application. For example, configuring a database connection and logging:
<pre class="language-python"><code>
import logging
import psycopg2
# Configure logging
logging.basicConfig(level=config['logging']['level'],
filename=config['logging']['file'],
format='%(asctime)s %(levelname)s:%(message)s')
# Connect to the database
conn = psycopg2.connect(
host=config['database']['host'],
port=config['database']['port'],
user=config['database']['user'],
password=config['database']['password']
)
logging.info('Application started')
logging.info('Connected to the database')
</code></pre>
</li>
</ul>
</li>
<li><strong>Advanced Configurations: </strong>YAML supports more complex data structures, which can be very useful for advanced configurations.
<ul>
<li><strong>Nested Configurations: </strong>You can nest configurations to represent complex settings:</li>
<pre class="language-python"><code>
server:
host: localhost
ports:
http: 80
https: 443
</code></pre>
<li><strong>Lists: </strong>YAML also supports lists, which can be useful for configurations like allowed hosts or user roles:</li>
<pre class="language-python"><code>
allowed_hosts:
- localhost
- 127.0.0.1
- example.com
user_roles:
- admin
- user
- guest
</code></pre>
<li><strong>Anchors and Aliases: </strong>YAML supports anchors and aliases to reuse parts of the configuration. This can help avoid redundancy:</li>
<pre class="language-python"><code>
defaults: &defaults
adapter: postgres
host: localhost
development:
<<: *defaults
database: dev_db
production:
<<: *defaults
database: prod_db
host: prod_host
</code></pre>
<li><strong>Error Handling: </strong>When working with configurations, it’s essential to handle errors gracefully. For example, checking if required fields are present and logging errors:</li>
<pre class="language-python"><code>
try:
db_host = config['database']['host']
except KeyError as e:
logging.error(f'Missing configuration for {e}')
raise
</code></pre>
</ul>
</li>
</ol>
A example complex yaml configuration file is:
<pre class="language-yaml" tabindex="0"><code class="language-yaml">
appName<span class="token punctuation">:</span> appName
logLevel<span class="token punctuation">:</span> WARN
AWS<span class="token punctuation">:</span>
Region<span class="token punctuation">:</span> us<span class="token punctuation">-</span>east<span class="token punctuation">-</span><span class="token number">1</span>
Resources<span class="token punctuation">:</span>
EC2</span><span class="token punctuation">:</span>
Type<span class="token punctuation">:</span> <span class="token string">"AWS::EC2::Instance"</span>
Properties<span class="token punctuation">:</span>
ImageId<span class="token punctuation">:</span> <span class="token string">"ami-0ff8a91507f77f867"</span>
InstanceType<span class="token punctuation">:</span> t2.micro
KeyName<span class="token punctuation">:</span> testkey
BlockDeviceMappings<span class="token punctuation">:</span>
<span class="token punctuation">-</span>
DeviceName<span class="token punctuation">:</span> /dev/sdm
Ebs<span class="token punctuation">:</span>
VolumeType<span class="token punctuation">:</span> io1
Iops<span class="token punctuation">:</span> <span class="token number">200</span>
DeleteOnTermination<span class="token punctuation">:</span> <span class="token boolean important">false</span>
VolumeSize<span class="token punctuation">:</span> <span class="token number">20</span>
Lambda<span class="token punctuation">:</span>
Type<span class="token punctuation">:</span> <span class="token string">"AWS::Lambda::Function"</span>
Properties<span class="token punctuation">:</span>
Handler<span class="token punctuation">:</span> <span class="token string">"index.handler"</span>
Role<span class="token punctuation">:</span>
Fn::GetAtt<span class="token punctuation">:</span>
<span class="token punctuation">-</span> <span class="token string">"LambdaExecutionRole"</span>
<span class="token punctuation">-</span> <span class="token string">"Arn"</span>
Runtime<span class="token punctuation">:</span> <span class="token string">"python3.7"</span>
Timeout<span class="token punctuation">:</span> <span class="token number">25</span>
TracingConfig<span class="token punctuation">:</span>
Mode<span class="token punctuation">:</span> <span class="token string">"Active"</span>
routes<span class="token punctuation">:</span>
admin<span class="token punctuation">:</span>
url<span class="token punctuation">:</span> /admin
template<span class="token punctuation">:</span> admin.html
assets<span class="token punctuation">:</span>
templates<span class="token punctuation">:</span> /templates
static<span class="token punctuation">:</span> /static
dashboard<span class="token punctuation">:</span>
url<span class="token punctuation">:</span> /dashboard
template<span class="token punctuation">:</span> dashboard.html
assets<span class="token punctuation">:</span>
templates<span class="token punctuation">:</span> /templates
static<span class="token punctuation">:</span> /static
account<span class="token punctuation">:</span>
url<span class="token punctuation">:</span> /account
template<span class="token punctuation">:</span> account.html
assets<span class="token punctuation">:</span>
templates<span class="token punctuation">:</span> /templates
static<span class="token punctuation">:</span> /static
databases<span class="token punctuation">:</span>
cassandra<span class="token punctuation">:</span>
host<span class="token punctuation">:</span> example.cassandra.db
username<span class="token punctuation">:</span> user
password<span class="token punctuation">:</span> password
redshift<span class="token punctuation">:</span>
jdbcURL<span class="token punctuation">:</span> jdbc<span class="token punctuation">:</span>redshift<span class="token punctuation">:</span>//<IP<span class="token punctuation">></span><span class="token punctuation">:</span><PORT<span class="token punctuation">></span>/file<span class="token punctuation">?</span>user=username<span class="token important">&password=pass</span>
tempS3Dir<span class="token punctuation">:</span> s3<span class="token punctuation">:</span>//path/to/redshift/temp/dir/
redis<span class="token punctuation">:</span>
host<span class="token punctuation">:</span> hostname
port<span class="token punctuation">:</span> port<span class="token punctuation">-</span>number
auth<span class="token punctuation">:</span> authentication
db<span class="token punctuation">:</span> databaseconfig.yaml
</code></pre>
In this case, we can read the yaml file as:
<pre class="language-python" tabindex="0"><code class="language-python">
# yaml_config.py
"""Load configuration from .yaml file."""
import confuse
config = confuse.Configuration('MyApp', __name__)
runtime = config['AWS']['Lambda']['Runtime'].get()
print(runtime)
</code></pre>
Confuse also gets into the realm of building CLIs, allowing us to use our YAML file to inform arguments which can be passed to a CLI and their potential values:
<pre class="language-python"><code>
# cli_config.py
config = confuse.Configuration('myapp')
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='a parameter')
args = parser.parse_args()
config.set_args(args)
print(config['foo'].get())
</code></pre>
</section>
<!-------Reference ------->
<section id="reference">
<h2>References</h2>
<ul>
<li><a href="https://hackersandslackers.com/simplify-your-python-projects-configuration/" target="_blank">Configuring Python Projects with INI, TOML, YAML, and ENV files.</a></li>
</ul>
</section>
<hr>
<div style="background-color: #f0f0f0; padding: 15px; border-radius: 5px;">
<h3>Some other interesting things to know:</h3>
<ul style="list-style-type: disc; margin-left: 30px;">
<li>Visit my website on <a href="sql-project.html">For Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.</a></li>
<li>Visit my website on <a href="Data-engineering.html">Data engineering</a></li>
</ul>
</div>
<p></p>
<div class="navigation">
<a href="index.html#portfolio" class="clickable-box">
<span class="arrow-left">Portfolio section</span>
</a>
<a href="Data-engineering.html" class="clickable-box">
<span class="arrow-right">Content</span>
</a>
</div>
</div>
</section><!-- End Portfolio Details Section -->
</main><!-- End #main -->
<!-- ======= Footer ======= -->
<footer id="footer">
<div class="container">
<div class="copyright">
© Copyright <strong><span>Arun</span></strong>
</div>
</div>
</footer><!-- End Footer -->
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>
<!-- Vendor JS Files -->
<script src="assets/vendor/purecounter/purecounter_vanilla.js"></script>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/vendor/typed.js/typed.umd.js"></script>
<script src="assets/vendor/waypoints/noframework.waypoints.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<!-- Template Main JS File -->
<script src="assets/js/main.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
hljs.initHighlightingOnLoad();
});
</script>
<!-- Initialize highlight.js -->
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightBlock(block);
});
});
</script>
</body>
</html>