mler notes
MLer index :
app.py
from flask import Flask, render_template
import business
app = Flask(__name__)
@app.route("/")
def index():
mler_data = business.get_data()
print(mler_data)
# return mler_data
return render_template("index.html",mler_datas=mler_data)
if __name__ == "__main__":
app.run(
port = 2345,
debug = True
)1
importing the required modules
from flask import Flask, render_template: This line imports the necessary modules from the Flask library.Flaskis used to create the Flask application, andrender_templateis used to render HTML templates.import business: This line imports thebusinessmodule. Presumably, this module contains the business logic of your application, such as database queries or data processing functions.
2
Creating the Flask Application Instance
app = Flask(__name__): This line creates an instance of the Flask class and assigns it to the variableapp. The__name__argument helps Flask determine the root path of the application so that it can find static files and templates.
3
Defining the Index Route
@app.route("/"): This line is a decorator that tells Flask that the functionindex()should be called whenever the root URL ("/") is accessed. This is typically the homepage of your web application.def index():: This line defines theindexfunction, which will be executed when the root URL is accessed.
4
Calling Business Logic and Rendering the Template
mler_data = business.get_data(): This line calls theget_data()function from thebusinessmodule and assigns its return value to themler_datavariable. Theget_data()function presumably retrieves data, perhaps from a database or API.
print(mler_data): This line prints themler_datavariable to the console. This is likely for debugging purposes so that you can see the data being retrieved.
return render_template("index.html", mler_datas=mler_data): This line renders theindex.htmltemplate and passes themler_datato it as a variable namedmler_datas. This allows the template to access and display the data within the HTML page.
5
Running the Flask Application
if __name__ == "__main__":This conditional checks if the script is being run directly (as opposed to being imported as a module). If it is, the code inside this block will be executed.app.run(port = 2345, debug = True): This line runs the Flask application on port2345. Thedebug=Trueargument enables debug mode, which provides detailed error messages and automatically reloads the server when code changes are detected.
create a variable "mler_list" because the value should be in the type of list inside the dictionary.
Inside the list hardcore the values of the user .json in dictionary formate.
1
Creating a List of Dictionaries
mler_list = [: This line defines a variable namedmler_listand assigns it a list. In Python, a list is an ordered collection of items, enclosed in square brackets[].
2
First Dictionary in the List
{ "name":"steve", "github_score":87 }: This is a dictionary, which is a collection of key-value pairs, enclosed in curly braces{}."name":"steve": This is a key-value pair where the key is"name"and the value is"steve"."github_score":87: This is another key-value pair where the key is"github_score"and the value is87.Together, this dictionary represents a data entry for someone named "steve" with a GitHub score of 87.
3
Second Dictionary in the List
{ "name":"sanjay", "github_score":78 }: This is another dictionary in the list."name":"sanjay": The key"name"has the value"sanjay"."github_score":78: The key"github_score"has the value78.This dictionary represents a data entry for someone named "sanjay" with a GitHub score of 78.
4
Closing the List
]: This closing bracket marks the end of the listmler_list.
1
use jinja template in Python, to print the value in the ui.
create an HTML file name like "index.html" use for loop in the index.html
1
Provided Code Explanation:
{% for mler_index %}:{% for ... %}: This is the start of a Jinja for loop. Jinja's{% %}syntax is used to denote statements or control structures, like loops and conditionals.mler_index: This is meant to be the loop variable that will represent each item in the sequence you want to iterate over. However, the sequence to iterate over is missing, so this line is incomplete and won't work as intended.
{% endfor %}:{% endfor %}: This marks the end of the for loop. Everything between{% for ... %}and{% endfor %}will be repeated for each item in the sequence.
5
call the value from the variable by jinja template like
6
without hardcoding the value, get it from the csv sheet. use pandas for read this csv file in business.py
the below code using read_csv function is used to read the "csv" file
7
when the read_csv function read as a tuple, but we need to been as a diction.
.to_dict('records')
This method converts the DataFrame into a dictionary or a list of dictionaries, depending on the parameter passed. When you use 'records' as the argument, each row in the DataFrame is converted into a dictionary where the keys are the column names and the values are the corresponding row values.
8
convert the above into method
The code mler_list = mler_df.to_dict('records') converts a DataFrame mler_df from the Pandas library into a list of dictionaries and stores it in the variable mler_list.
Here's a breakdown of what this code does:
mler_df: This is assumed to be a Pandas DataFrame. A DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns)..to_dict('records'): This method converts the DataFrame into a dictionary or a list of dictionaries, depending on the parameter passed. When you use'records'as the argument, each row in the DataFrame is converted into a dictionary where the keys are the column names and the values are the corresponding row values.For example, if
mler_dflooks like this:NameAgeRatingAlice
25
8.5
Bob
22
7.8
Then,
mler_df.to_dict('records')would convert it into:mler_list: This variable holds the result of the conversion, which is a list of dictionaries. Each dictionary represents a row from the original DataFrame.
In summary, mler_list = mler_df.to_dict('records') converts the DataFrame mler_df into a list of dictionaries, where each dictionary corresponds to a row in the DataFrame, making it easier to work with row data in a more flexible format (e.g., for iterating, storing in a database, etc.).
9
call the function in the flask program , use these below to import the business file in the flask code
The statement import business as bus is a Python import statement that allows you to import a module named business and give it an alias (bus) for easier reference throughout your code.
Here's a breakdown of what this means:
import business: This part tells Python to import a module namedbusiness. A module in Python is a file containing Python code (functions, classes, variables, etc.) that you can reuse in other Python programs. Thebusinessmodule could be a file namedbusiness.pyin the same directory as your script, or it could be a module installed in your environment.as bus: Theaskeyword allows you to assign an alias to the module you are importing. In this case, instead of referring to the module asbusinessin your code, you can refer to it asbus.This can be useful for shortening long module names, avoiding conflicts with other variable names, or simply making the code more readable.
For example, instead of writing:
You can write:
This aliasing is particularly helpful if the module name is long or if you want to standardize naming across your project.
So, import business as bus imports the business module and allows you to use bus as a shorthand name for it in your code.
Get key by value in python
Method 1: Using a Loop
Method 2: Using Dictionary Comprehension
In both methods, key will be set to 'b' because it is the key associated with the value 2. If the value is not found, None will be returned using the dictionary comprehension method.
Line 1: A dictionary named my_dict is created with three key-value pairs: 'a': 1, 'b': 2, and 'c': 3. In this dictionary, 'a' is associated with 1, 'b' with 2, and 'c' with 3.
Line 2: A variable value_to_find is initialized with the value 2. This is the value you want to search for in the dictionary.
Line 3: A
forloop starts, iterating over the key-value pairs in the dictionary. Themy_dict.items()method returns a view object that displays a list of a dictionary's key-value tuple pairs, like('a', 1),('b', 2),('c', 3).Each iteration of the loop assigns the current key to
keyand the corresponding value tovalue.
Line 4: Inside the loop, an if statement checks whether the current value is equal to value_to_find. If this condition is true, the code inside the if block will execute.
Why this code rerurns A view of object that display list of dictionaries key value as a tuple pair like
The line for key, value in my_dict.items(): doesn't directly return a view or a list. Instead, it iterates over a view object returned by my_dict.items().
Explanation:
my_dict.items():This method returns a view object that displays a dynamic view of the dictionary's key-value pairs.
The view object behaves like a collection of tuples, where each tuple is a pair consisting of a key and its corresponding value.
For example, if
my_dict = {'a': 1, 'b': 2, 'c': 3}, thenmy_dict.items()will produce a view object containing('a', 1),('b', 2), and('c', 3).
Iteration Over my_dict.items():
my_dict.items():for key, value in my_dict.items()::This loop iterates over the view object returned by
my_dict.items().During each iteration, it unpacks a tuple into two variables:
keyandvalue.First iteration:
keyis'a', andvalueis1.Second iteration:
keyis'b', andvalueis2.Third iteration:
keyis'c', andvalueis3.
These key-value pairs are processed one by one within the loop.
Why it Returns a View Object:
Efficiency: The view object returned by
my_dict.items()doesn't create a separate list of tuples; instead, it provides a dynamic view of the dictionary's items. This makes it more memory-efficient, especially for large dictionaries.Dynamic Nature: Since the view object is dynamic, it reflects any changes made to the dictionary even after the view has been created.
In summary, my_dict.items() gives you a view of the dictionary's key-value pairs as tuples, and the for key, value in my_dict.items(): loop unpacks and iterates over these tuples.
Give me an alternative for this method
1. Using a for Loop with Dictionary Keys:
You can iterate over the dictionary keys and access their corresponding values using the key directly.
Explanation: This loop goes through each key in my_dict, and for each key, it fetches the value using my_dict[key].
2. Using List Comprehension:
You can create a list of tuples representing key-value pairs using list comprehension.
Explanation: This approach constructs a list of tuples where each tuple contains a key and its corresponding value.
3. Using the zip() Function:
zip() Function:You can zip the dictionary's keys and values to create pairs.
Explanation: zip() pairs up the keys and values from the dictionary, and list() converts the result into a list of tuples.
4. Using the enumerate() Function (for indexed iteration):
enumerate() Function (for indexed iteration):If you want to access the index along with the key-value pairs, enumerate() can be useful.
Explanation: enumerate() gives you both the index and the key-value pair, which can be helpful in scenarios where you need the position as well.
5. Manual Key-Value Pair Collection:
You can manually build a list of key-value tuples by iterating over the keys.
Explanation: This method explicitly constructs a list of tuples by iterating over the keys and appending each key-value pair.
Summary:
The
items()method is convenient and efficient, but these alternatives provide flexibility depending on the context.Using loops, list comprehensions, or functions like
zip()can achieve similar results if you prefer or need a different approach.
Last updated