<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: bellagerken</title>
    <description>The latest articles on DEV Community by bellagerken (@bellagerken).</description>
    <link>https://dev.to/bellagerken</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1071714%2Fcfabe58c-5eea-49ce-88ce-150b2fd34707.png</url>
      <title>DEV Community: bellagerken</title>
      <link>https://dev.to/bellagerken</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/bellagerken"/>
    <language>en</language>
    <item>
      <title>User authentication in flask / react</title>
      <dc:creator>bellagerken</dc:creator>
      <pubDate>Wed, 19 Jul 2023 14:46:46 +0000</pubDate>
      <link>https://dev.to/bellagerken/user-authentication-in-flask-react-4269</link>
      <guid>https://dev.to/bellagerken/user-authentication-in-flask-react-4269</guid>
      <description>&lt;p&gt;In order to allow users to login to a website and identify themselves, we can implement authentication into our application. To do this, we need to implement the use of cookies and sessions. Cookies are information that gets sent to client from the server. That information gets stored on the browser and each request that follows get sent back to the server. A session allows users to be remembered, where cookies can track user interaction throughout the duration of their session. &lt;/p&gt;

&lt;p&gt;In order to begin the process of authenticating users, we must set up a POST login in the backend. Doing this would look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Login(Resource):

    def post(self):
        user = User.query.filter(
            User.username == request.get_json()['username']
        ).first()

        session['user_id'] = user.id
        return user.to_dict()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows users to post a username and begin a session. On the frontend side, it would look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Login({ onLogin }) {
  const [username, setUsername] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    fetch("/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username }),
    })
      .then((r) =&amp;gt; r.json())
      .then((user) =&amp;gt; onLogin(user));
  }

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;input
        type="text"
        value={username}
        onChange={(e) =&amp;gt; setUsername(e.target.value)}
      /&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Login&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates a form for the user to enter in their information, and once they click submit their login info will be posted to the back-end and the session will begin. &lt;/p&gt;

&lt;p&gt;A problem that arises after logging in is if the user refreshes the page, the front-end has no way of remembering who they are. In order to solve this problem, we can implement a class starting in the back-end called "check_session". The code for this class would look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CheckSession(Resource):

    def get(self):
        user = User.query.filter(User.id == session.get('user_id')).first()
        if user:
            return user.to_dict()
        else:
            return {'message': '401: Not Authorized'}, 401

api.add_resource(CheckSession, '/check_session')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the front-end:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [user, setUser] = useState(null);

  useEffect(() =&amp;gt; {
    fetch("/check_session").then((response) =&amp;gt; {
      if (response.ok) {
        response.json().then((user) =&amp;gt; setUser(user));
      }
    });
  }, []);

  if (user) {
    return &amp;lt;h2&amp;gt;Welcome, {user.username}!&amp;lt;/h2&amp;gt;;
  } else {
    return &amp;lt;Login onLogin={setUser} /&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are using state to keep the user logged in after checking to see if there is a session running.&lt;/p&gt;

&lt;p&gt;Lastly, to log the user out of the session the solution is simple. From the backend, the code will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Logout(Resource):

    def delete(self):
        session['user_id'] = None
        return {'message': '204: No Content'}, 204

api.add_resource(Logout, '/logout')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simply put - the backend sets the session equal to none. On the front end, the code looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Navbar({ onLogout }) {
  function handleLogout() {
    fetch("/logout", {
      method: "DELETE",
    }).then(() =&amp;gt; onLogout());
  }

  return (
    &amp;lt;header&amp;gt;
      &amp;lt;button onClick={handleLogout}&amp;gt;Logout&amp;lt;/button&amp;gt;
    &amp;lt;/header&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the user clicks on the button, they will log themselves out and the session will end. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to build a GET Api using Flask</title>
      <dc:creator>bellagerken</dc:creator>
      <pubDate>Fri, 30 Jun 2023 12:20:40 +0000</pubDate>
      <link>https://dev.to/bellagerken/how-to-build-a-get-api-using-flask-e27</link>
      <guid>https://dev.to/bellagerken/how-to-build-a-get-api-using-flask-e27</guid>
      <description>&lt;p&gt;In order to make a GET request in a front end React application from the server, the server needs to be set up in that it sends an object array in JSON format. On the front end, you might see something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function tripList() {
  const [trips, setTrips] = useState([]);

  useEffect(() =&amp;gt; {
    fetch("http://localhost:4000/trips")
      .then((r) =&amp;gt; r.json())
      .then((trips) =&amp;gt; setTrips(trips));
  }, []);

  return (
    &amp;lt;section&amp;gt;
      {trips.map((trip) =&amp;gt; (
        &amp;lt;TripItem key={trip.id} trip={trip} /&amp;gt;
      ))}
    &amp;lt;/section&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To set up the back end of the GET request, there are some initializers to be set up first. At the top of an app.py file, you will start with something that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

from models import db, User, Review, Game

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.json.compact = False

migrate = Migrate(app, db)

db.init_app(app)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using jsonify allows us to serialize our arguments (lists or dictionaries) as JSON and subsequently returns a response. make_response is what is used to send back the data. To begin setting up the GET request, we can start by settings up an @app.route('/trips') to our list of trips. From there, we want to define a function called def trips. Next, the idea is to grab all of the trips that we have a put them in a list, which we will then jsonify and send the response via make_response. To begin, we want to set up an empty list and set it equal to a variable such as "trips". Next, we will use query to get all of our trips which will look like: Trips.query.all(). However, it's important to serialize each trips in all trips and to resolve that issue we can create a for loop. Within the for loop, the next step is to create the dictionary object for the trip. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for trip in Trips.query.all():
    trip_dict = {
       "date": trip.date,
       "location": trip.location
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we want to append these trip_dict's to the empty list that we created. After that, we can create a variable called "response" and set it equal to make_response(jsonify(trips), 200). Lastly within the function we want to return the response! This is how you set up a GET request in Flask. See below for the full code under @app.route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/trips')
def trips():

    trips = []
    for trip in Trip.query.all():
        trip_dict = {
            "date": trip.date,
            "location": trip.location,
        }
        trips.append(trip_dict)

    response = make_response(
        trips,
        200,
        {"Content-Type": "application/json"}
    )

    return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>How to create a game of hangman in python</title>
      <dc:creator>bellagerken</dc:creator>
      <pubDate>Fri, 09 Jun 2023 12:07:46 +0000</pubDate>
      <link>https://dev.to/bellagerken/how-to-create-a-game-of-hangman-in-python-1373</link>
      <guid>https://dev.to/bellagerken/how-to-create-a-game-of-hangman-in-python-1373</guid>
      <description>&lt;p&gt;def get_word():&lt;/p&gt;

&lt;p&gt;The very first thing to be done is create a list of possible words to be stored as a variable called word_list. Then call the random.choice method in order to get a new word each time the user plays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;word = random.choice(word_list)
        return word.upper()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;def play(word):&lt;/p&gt;

&lt;p&gt;Next create a method that contains all the code for playing the game. To start, you can declare a few variables and printed a few statements like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print("Let's play Hangman!")
print(display_hangman(tries))
print(word_completion)
print("\n")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;"word_completion" represents underscore symbols times the length of the random word that was chosen. "guessed" represents whether or not yet the player has correctly entered all the right letters of the word. The letters and words that the player guesses will be appended to a list, and tries represents how many more chances they have until the hangman is complete. Additionally, there are some statements that direct the user to play, and print(display_hangman(tries)) refers to the next method to be created in which 7 different hangman stages will need to be created and stored as a list. The index of each hangman will be related to the number of tries the player still has to guess the correct answer. Additionally, the empty underscores will be shown to the player (word_completion) before the game begins.&lt;/p&gt;

&lt;p&gt;The next step is to start a while loop as the user has not guessed the answer and their tries to win are greater than 0. To begin, initialize a variable called guess and set it equal to input("Please guess a letter or word: ").upper() where the player will enter their guess. Then, create an if/else statement block that first checks if the length of the guess is equal to 1 and if it is apart of the alphabet. Within that 'if' statement, create another that checks if 'guess' is in 'guessed_letters', and print: print("You already guessed the letter", guess). If guess is not in the word: print(guess, "is not in the word."). Here, the 'tries' variable will decrease by 1 (which will also cause the hangman to gain a body part since tries is related to its index), and the empty guess_letters list will append the guess. Else, if the guess is in the word, create a print statement that notifies the player, append the guess to 'guessed_letters', and create a variable for creating a list of 'word_completion'. &lt;/p&gt;

&lt;p&gt;In relation to the first if statement created, finish it by then creating an elif statement that checks if the length of the guess is equal to the length of the word (and is a part of the alphabet). Within that elif statement create another if statement that checks if guess is in guessed words in which print: print("You already guessed the word", guess). If not in the word, print: print(guess, "is not the word."). Decrease the tries by one and append the guess to 'guessed_words' list. Else, guess = True and word_completion = word. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;else:
        print("Not a valid guess.")
    print(display_hangman(tries))
    print(word_completion)
    print("\n")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Lastly, create a print statement if the player correctly guessed the word that says something like:&lt;/p&gt;

&lt;p&gt;if guessed:&lt;br&gt;
        print("Congrats, you guessed the word! You win!")&lt;/p&gt;

&lt;p&gt;else:&lt;br&gt;
        print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!")&lt;/p&gt;

&lt;p&gt;Now your hangman code is complete! &lt;/p&gt;

&lt;p&gt;For reference, see below an example of how you can create a visual hangman:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def display_hangman(tries):
    stages = [ 
                """
                   --------
                   |      |
                   |      🤠
                   |    👋👔👋
                   |      👖
                   |     👟👟
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      🤠
                   |    👋👔👋
                   |      👖
                   |     👟
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      🤠
                   |    👋👔👋
                   |      👖
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      🤠
                   |    👋👔
                   |      👖
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      🤠
                   |      👔
                   |      👖
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      🤠
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[tries]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>What I learned about React Components</title>
      <dc:creator>bellagerken</dc:creator>
      <pubDate>Wed, 17 May 2023 12:02:46 +0000</pubDate>
      <link>https://dev.to/bellagerken/what-i-learned-about-react-components-14cf</link>
      <guid>https://dev.to/bellagerken/what-i-learned-about-react-components-14cf</guid>
      <description>&lt;p&gt;When learning Javascript for the first time, all of our code to render information on a webpage was on one index.js file. While this is convenient for a small website, as more complex websites are built with lots of different pieces, it can be difficult to keep your code organized. &lt;/p&gt;

&lt;p&gt;React introduces a way to organize your data in a way that will allow the programmer to render independent and reusable pieces to the DOM. Components contribute to the functionality and presentation of our code, which becomes more and more helpful as our web applications become more complex. The simple goal of a React component is to contain a smaller section of code that describes what should be rendered to the &lt;br&gt;
DOM. &lt;/p&gt;

&lt;p&gt;In order to write a component, we must declare a function and name it starting with a capital letter. The capital letter differentiates javascript functions from react components, and must be used in order to render the components to the DOM. The return value for the function contains a snippet of JSX. The beauty of a React component is that if we then wanted to render this JSX multiple times, we could repeatedly call on this component so that is gets rendered with no variations. It is almost as if components are like functions for rendering sections of JSX to the DOM. &lt;/p&gt;

&lt;p&gt;An example of a component that would create a header tag is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Header(){
  return(
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Hello&amp;lt;/h1&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Header
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When finished writing a component, we export it and import it to its parent component in which it will use in its return statement. It is common of react applications to contain one main component, typically called App.js, that renders the application's top-level components. &lt;/p&gt;

&lt;p&gt;An example of how a our Header component would be imported and returned in its parent (App) component is detailed below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Header from "./Header"

function App(){
  return(
    &amp;lt;div&amp;gt;
      &amp;lt;Header/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this translates to is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App(){
  return(
    &amp;lt;div&amp;gt;
      Hello
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Overall, React components make a programmer's life much easier by organizing their code in a way that renders JSX through small sections of code that are independent, and reusable. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>What I learned about scope</title>
      <dc:creator>bellagerken</dc:creator>
      <pubDate>Wed, 26 Apr 2023 12:44:37 +0000</pubDate>
      <link>https://dev.to/bellagerken/what-i-learned-about-scope-2og6</link>
      <guid>https://dev.to/bellagerken/what-i-learned-about-scope-2og6</guid>
      <description>&lt;p&gt;As a beginner learning javascript, the concept of “scope” was a particularly difficult one for me to grasp. However, as difficult as it was, understanding it has drastically transformed my ability to create and execute my code. Scope is the concept of whether or not we have access to variables and functions depending on where they are declared. When a variable is declared outside of a function, regardless if it’s declared with const, let, or var, that variable has what we call “global scope”. When a variable has global scope, it means we are able to access that variable everywhere in our program. Similarly, when a function is declared using the “function” declaration, accessing it has global scope because it isn’t nested within another function. With this being said, functions and variables that are declared within a function have what we call function scope. This means that they are only accessible within the function they were declared in and nowhere else. &lt;/p&gt;

&lt;p&gt;For example, if I declared a function and variable such as:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myFunction(){
    const myVariable = “hello”
    return myVariable;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If I tried to invoke “myVariable” outside of this function, javascript wouldn’t know what I was referencing and would likely return “undefined”.&lt;/p&gt;

&lt;p&gt;Another concept that I learned while about scope is the concept of “parent scope”. As you may know, multiple functions can be nested within each other creating a chain. “Scope chain” is what we call the concept of which functions have access to which variables, and functions only have access to the variables declared in its parent functions. For example, when we declare a second function inside a first, the second function has access to the first function, also known as it’s parent function, as well as anything declared globally. However, the first function declared does not have access to the variables declared within the second function. As the third, fourth, fifth, and so-on functions get declared in the chain, the bottom ones have access to what is above them, but not below. Lastly, I learned that statements containing blocks also create their own scope, however, when variables are declared with “var” instead of “const” or “let”, they maintain their global scope. This is why it is important to use “var” with caution, and remains safer to use “const” or “let”.&lt;/p&gt;

&lt;p&gt;When practicing for our class code challenge, the concept of scope became very prevalent while creating my code. While declaring my variables, I had initially started out declaring all of them within the first function I was using. &lt;/p&gt;

&lt;p&gt;Take a look at a section of my code here:&lt;/p&gt;

&lt;p&gt;function displayFirstCake(firstcake){&lt;br&gt;
   const cakeName = document.getElementById('cake-name')&lt;br&gt;
   const cakedescription = document.getElementById('cake-description')&lt;br&gt;
   const cakeImage = document.getElementById('cake-image')&lt;br&gt;
   const cakeReviews = document.getElementById('review-list')&lt;br&gt;
   cakeName.textContent = firstcake.name&lt;br&gt;
   cakedescription.textContent = firstcake.description&lt;br&gt;
   cakeImage.src = firstcake.image_url&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;However, later when I declared a new function and was trying to access the variable “cake reviews”, I wasn’t able to because it contained function scope and not global scope. It was here when I decided to move all my variables declared into global scope (outside of this function) because that would mean I had access within both of my functions. However, another alternative would’ve been to declare the same variable in my new function. Because my new function didn’t have access to the previous one, the same name for the variable could’ve been used in my new function as well without getting javascript confused. &lt;/p&gt;

&lt;p&gt;Additionally, another method I used when I was struggling with the scope of my variables was to declare a variable using “let” in global scope. When I set it equal to a value in one function, then I was able to access that value in another function. This is because using “let” allows for the value of the variables to change, and also since it was declared globally, I had access to it wherever I needed. Knowing this ended up being very helpful while practicing for my code challenge. &lt;/p&gt;

&lt;p&gt;Learning the concept of scope was crucial to my ability to learn and use javascript. Without this knowledge, one can spend an enormous amount of unnecessary time struggling to access their variables and functions. I know I will use this knowledge indefinitely throughout my coding career!&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
