One place for hosting & domains

      Library

      Decoding WordPress: The Media Library


      The WordPress Block Editor enables you to upload images and files directly to your site’s posts and pages. However, your media collection can become disorganized over time, and you might struggle to find media that you uploaded in the past.

      Fortunately, you can use the WordPress Media Library to organize your images and files. Thanks to multiple views and filters, you can develop an effective organizational system for your uploaded files. Additionally, you can optimize your images to rank higher in search results.

      In this post, we’ll give you an overview of the WordPress Media Library and its main features. Then, we’ll show you how to extend these features and fix any potential errors that occur. Let’s get started!

      An Introduction to the WordPress Media Library

      When you upload images, videos, and audio files to your WordPress website, these are stored in your Media Library. Essentially, this catalogs every piece of media you’ve used in your posts and pages.

      To open the Media Library, click on the Media tab in your admin dashboard. Then, you’ll be able to view your files and upload new ones if needed:

      WordPress Media Library

      Here are some files you may see in the Media Library:

      • Images (.jpeg, .jpeg, .png, .gif, .ico)
      • Audio files (.mp3, .m4a, .ogg, .wav)
      • Videos (.mp4, .mov, .wmv, .avi, .mpg, .ogv, .3gp, .3g2)
      • Documents (.pdf. .doc, .docx, .odt, .psd)
      • Spreadsheets (.xls, .xlsx)
      • Powerpoint presentations (.pps, .ppsx, .ppt, .pptx)

      If you need to narrow down your results by type, you can use the dropdown menu. Here, you’ll see the file types listed above, along with items labeled Unattached, Archives, and Mine:

      Media type

      You can also select a specific upload date. This can be particularly helpful if you’re unable to find an image but you know when it was uploaded:

      Upload date

      To organize your Media Library, you can use the Bulk select button. Then, you can select multiple images and delete them permanently:

      Bulk select

      In the top-right corner, you’ll see a search bar. Here, you can enter keywords to filter your results:

      Search Media Library

      Please note that you’ll have to have tagged the images with these keywords beforehand — but adding this little bit of extra effort to your workflow can make a huge difference when you’re trying to find things in the future.

      As you can see, the Media Library can help you organize the files on your website. It provides an all-in-one solution for uploading, editing, and deleting files.

      5 Useful Media Library Features

      If you’re new to WordPress, you might not know how to use the Media Library. Fortunately, this tool is very user-friendly, and it enables you to upload, view, and edit media files on your website. Let’s take a look at its main features.

      1. Multiple Views

      The Media Library lets you change the way files are displayed. You can either view them in a grid or a list.

      By default, the Media Library shows items in a grid view, with a thumbnail for each file:

      Grid view

      As we mentioned earlier, you can filter the results by media type and date. If you want to view the details of a certain file, you just have to click on it:

      Grid view attachment details

      Alternatively, you can switch to the list view. Instead of a gallery-like grid, your files will be displayed in a list:

      List view

      On the left-hand side, you can use the checkboxes to bulk-select files. Next to this, you’ll see a thumbnail representing each media item.

      Here’s what else you can see in a list view:

      • File: The file title, as well as the full name of the file.
      • Author: The user that uploaded the file.
      • Uploaded to: The title of the post or page where the file was uploaded.
      • Comment bubble: The number of comments for that file.
      • Date: The date when the media was uploaded.

      If you click on the file name, this will open the image editor:

      List view image editor

      You can switch between these two views at any time, depending on your preference. However, the list view can be a better option if you want to view a file’s details without having to click on it.

      2. Multiple Ways to Upload Files

      When you need to upload a file to your website, you can add it directly to a post or page. The Block Editor lets you add images, videos, and other files with blocks:

      Image block

      Once you select the relevant block, you can click on Upload and choose a file from your computer. If you’ve uploaded the file to WordPress before, you can select it from your Media Library:

      Upload from Media Library

      You can also drag and drop a file directly into this section. This will automatically upload it into the Media Library, and you can then add it to the post:

      Upload new file

      You can also upload images directly to the Media Library. Simply click on Add New, then drag and drop files into the upload area or select them from your computer:

      Add new media file

      With any of these methods, your media files will be automatically imported into WordPress. Even if you uploaded your files in the Block Editor, you’ll still be able to find them in the Media Library.

      3. Downloadable Files

      The Media Library also lets you download your files to your computer. This can be useful if you need to use the same images or videos on another site.

      To download a file from your WordPress dashboard, click on the Tools tab and select Export:

      WordPress export

      On this page, you can download all of your site’s content. This includes posts, pages, and media files.

      Select Media, then use the dropdown menus to download files that were uploaded within a certain timeframe. You’ll simply have to specify a Start date and End date:

      Export media

      If you want to download all of your media files, you can leave these fields blank. When you’re finished, click on Download Export File. This will download links to the relevant files to your computer in an XML file format that can then be imported into another WordPress install.

      4. Image Editing

      As a website owner, it’s vital that you optimize your images before publishing them. Large files can slow down your site and take up a lot of storage space.

      The Media Library has many native image editing features. For example, you can crop your images, scale them, and more.

      Start by clicking on an image to open the Attachment details page. Then, under the photo, select the Edit image button:

      Edit image

      This will automatically open the image editor. On the left, you’ll see options to crop, rotate, or flip the image:

      Image editing features

      If you select the Crop button, you can use the handles on the box to remove certain parts of the image. When you’re finished, click on Crop again:

      Crop image

      Using the rotate options, you can flip the image 90 degrees to the left or right:

      Rotate image

      If you need to invert the image, you can use the Flip buttons. These will reflect the photo vertically or horizontally:

      Flip image

      On the right side of the page, you’ll see the original dimensions of the image. To scale the image, you’ll just need to enter the new dimensions:

      Scale image

      Additionally, you can click on the Crop button and enter the size in the Selection fields. You can also choose an Aspect ratio, which is the relationship between the height and width of the image:

      Image crop selection

      The last feature you’ll see in the image editor is the Thumbnail Settings. Here, you can apply your changes to all image sizes, the thumbnail only, or all sizes except the thumbnail:

      Thumbnail settings

      When you’re finished, save your changes. You can now view the edited photo in the Media Library.

      5. Image Metadata

      In the Attachment details page of your image, you’ll see an option to add metadata. This contains basic information about the image, including the file name, author, and description:

      Image metadata

      After you upload an image, WordPress will use the file name as its title. However, you can edit this to provide a more accurate description:

      Image title

      You can also add alternative text. This describes the contents of the image when it can’t be displayed. Additionally, it can make your website more accessible to users with screen readers:

      Add alt text

      Along with improving user experience, alternative text can boost your search ranking. It enables search engines to understand your images and their purpose on the page.

      You might also want to write a caption and description to provide more information about the image. While the alt text is only visible to search engines and screen readers, the caption is visible to all front-end users:

      Image caption

      Meanwhile, descriptions will appear on the image attachment page. Here, you can post copyright details, keywords, links, and more:

      Image description

      This information will be saved in the Media Library. When someone visits the image URL, they’ll be able to see its description.

      How to Extend the Features in the Media Library

      The Media Library provides the essential tools you need to upload and edit media files. However, you may need to install a plugin to extend its core functionality.

      As you upload more images to your website, your Media Library can get a little disorganized. Although you can delete images in bulk and use filters to find what you need, you may become overwhelmed by the volumes of files on your website.

      With the Real Media Library plugin, you can create folders in your Media Library:

      Real Media Library

      This tool has a drag-and-drop interface that enables you to easily move media items to different sections. Plus, the pro version supports subfolders, image galleries, and rearranging within a folder.

      Alternatively, you can use the free version of Media Library Organizer to add media categories for better media management:

      Media Library Organizer

      The native editing features in the Media Library may not fully optimize your images. Often, you’ll need to compress image files in order to speed up your website.

      With the TinyPNG plugin, you can let your WordPress install automatically compress your images as you upload them:

      TinyPNG plugin

      Additionally, you may want to replace old files with newer versions. With the Media Library, you’ll have to upload the new file, locate the old version, and delete it.

      Enable Media Replace is a popular WordPress plugin that you can use to quickly replace files in your Media Library:

      Enable Media Replace

      Even though you might not need these tools, they are available to help you optimize your website and manage your files more efficiently. They can be particularly useful when activated on media-heavy sites.

      How to Fix Common Media Library Errors

      Although the Media Library is very user-friendly, you might run into some common image upload issues. Fortunately, most of these problems are easy to fix.

      HTTP Error

      One of the most common issues in the Media Library is an undefined HTTP error. This crops up when something goes wrong during the upload process.

      When this happens, it’s a good idea to wait a few minutes before trying to upload the file again. Sometimes, it’s just a temporary resource allocation problem.

      Alternatively, this common image error could be caused by your browser. You can try switching to another browser to see if it solves the problem.

      If the error persists, you can try clearing your browser cache and deactivating your plugins. Alternatively, you might need to increase your site’s memory limit.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      Upload: Failed to Write File to Disk

      When you’re uploading files to your website, you may also come across the Upload: Failed to Write File to Disk error. Usually, this results from incorrect file permissions. However, you could have maxed out your hosting plan’s disk space limit or temporary folder.

      To fix this error, you’ll need to check the file permissions for your website. First, you’ll need to connect to a Secure File Transfer Protocol (SFTP) client to access your site files. Alternatively, you can use the File Manager in your hosting account.

      If you have a DreamHost account, open your dashboard and go to Websites > Files and FTP Users:

      DreamHost manage files

      Then, click on Manage Files next to your website. In your File Manager, find the wp-content file and right-click on it:

      Open file permissions

      For DreamHost accounts, you can select CHMOD. If you’re using another program, click on the File Permissions option. This will open a pop-up window:

      File permissions

      Make sure the Numeric value is set to ‘755’. Then, click on OK to save your changes. This should help resolve the issue.

      Media Library Failing to Load

      Occasionally, your Media Library might fail to load altogether. This can happen if you’re using a poorly-coded theme or plugin.

      You might also see this error when there’s a conflict between two plugins. Third-party software can cause compatibility issues with other programs.

      To resolve the issue, start by deactivating your plugins. Select them all, then choose Deactivate from the Bulk actions menu and hit Apply:

      Deactivate plugins

      Now, refresh the Media Library page to see if this solved the problem. If so, you’ll need to reactivate each plugin one at a time and keep refreshing the Media Library until the issue reappears. This should help you identify the culprit.

      If deactivating the plugins doesn’t help, then the problem might be your theme. Consider activating a default WordPress theme, then try accessing your Media Library again.

      Organize Your WordPress Images

      The WordPress Media Library enables you to upload, modify, and delete files on your website. You can also use it to crop and scale images without leaving your dashboard.

      To review, here are the main things you can do in the Media Library:

      1. View uploads in a grid or list view.
      2. Upload files in the Media Library or Block Editor.
      3. Download files to your computer.
      4. Edit image size, pixels, and orientation.
      5. Add image metadata.

      Although optimizing images can improve your loading times, you’ll want to build a fast website from the ground up. Our managed WordPress hosting plans come with several performance tools to help you grow your site. Check out our plans today!

      Do More with DreamPress

      DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

      Managed WordPress Hosting - DreamPress



      Source link

      How To Create an Intelligent Chatbot in Python Using the spaCy NLP Library


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Interacting with software can be a daunting task in cases where there are a lot of features. In some cases, performing similar actions requires repeating steps, like navigating menus or filling forms each time an action is performed. Chatbots are virtual assistants that help users of a software system access information or perform actions without having to go through long processes. Many of these assistants are conversational, and that provides a more natural way to interact with the system.

      To create a conversational chatbot, you could use platforms like Dialogflow that help you design chatbots at a high level. Or, you can build one yourself using a library like spaCy, which is a fast and robust Python-based natural language processing (NLP) library. spaCy provides helpful features like determining the parts of speech that words belong to in a statement, finding how similar two statements are in meaning, and so on.

      In this tutorial, you will create a chatbot that not only helps users simplify their interactions with a software system, but is also intelligent enough to communicate with the user in natural language (American English in this tutorial). The chatbot will use the OpenWeather API to tell the user what the current weather is in any city of the world, but you can implement your chatbot to handle a use case with another API.

      Prerequisites

      Before you begin, you will need the following:

      This tutorial assumes you are already familiar with Python—if you would like to improve your knowledge of Python, check out our How To Code in Python 3 series. This tutorial does not require foreknowledge of natural language processing.

      Step 1 — Setting Up Your Environment

      In this step, you will install the spaCy library that will help your chatbot understand the user’s sentences.

      Having set up Python following the Prerequisites, you’ll have a virtual environment. Let’s activate that environment.

      Make sure you are in the directory where you set up your environment and then run the following command:

      • source my_env/bin/activate

      Now install spaCy:

      Finally, you will download a language model. spaCy’s language models are pre-trained NLP models that you can use to process statements to extract meaning. You’ll be working with the English language model, so you’ll download that.

      Run the following command:

      • python -m spacy download en_core_web_md

      If you run into an error like the following:

      Output

      ERROR: Failed building wheel for en-core-web-md

      You need to install wheel:

      Then download the English-language model again.

      To confirm that you have spaCy installed properly, open the Python interpreter:

      Next, import spaCy and load the English-language model:

      >>> import spacy
      >>> nlp = spacy.load("en_core_web_md")
      

      If those two statements execute without any errors, then you have spaCy installed.

      Now close the Python interpreter:

      >>> exit()
      

      You now have everything needed to begin working on the chatbot. In the next section, you’ll create a script to query the OpenWeather API for the current weather in a city.

      Step 2 — Creating the City Weather Program

      In this section, you will create a script that accepts a city name from the user, queries the OpenWeather API for the current weather in that city, and displays the response.

      First, create and open a Python file called weather_bot.py with your preferred editor:

      Next, you’ll create a function to get the current weather in a city from the OpenWeather API. This function will take the city name as a parameter and return the weather description of the city.

      Add the following code into your weather_bot.py file:

      weather_bot.py

      import requests
      
      api_key = "your_api_key"
      
      def get_weather(city_name):
          api_url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(city_name, api_key)
      
          response = requests.get(api_url)
          response_dict = response.json()
      
          weather = response_dict["weather"][0]["description"]
      
          if response.status_code == 200:
              return weather
          else:
              print('[!] HTTP {0} calling [{1}]'.format(response.status_code, api_url))
              return None
      

      First, you import the requests library, so you are able to work with and make HTTP requests. Make sure to replace your_api_key with your own API key. The next line begins the definition of the function get_weather() to retrieve the weather of the specified city.

      In this function, you construct the URL for the OpenWeather API. This URL returns the weather information (temperature, weather description, humidity, and so on) of the city and provides the result in JSON format. After that, you make a GET request to the API endpoint, store the result in a response variable, and then convert the response to a Python dictionary for easier access.

      On the next line, you extract just the weather description into a weather variable and then ensure that the status code of the API response is 200 (meaning there were no issues with the request). Finally, you return the weather description.

      If there is an issue with the request, the status code is printed out to the console, and you return None.

      To test the script, call the get_weather() function with a city of your choice (for example, London) and print the result. Add the highlighted code following your function:

      ~/weather_bot.py

      import requests
      
      def get_weather(city_name):
      
        ...
      
        return weather
      
      weather = get_weather("London")
      print(weather)
      

      Save and run the script:

      You will receive a result like the following:

      Output

      scattered clouds

      Having completed that successfully, you can now delete the last two lines from the script.

      Open it with:

      Then delete the two highlighted lines at the end of the file:

      ~/weather_bot.py

      import requests
      
      def get_weather(city_name):
      
        ...
      
        return weather
      
      weather = get_weather("London")
      print(weather)
      

      Save and close the file.

      You now have a function that returns the weather description for a particular city.

      In the next step, you’ll create a chatbot capable of figuring out whether the user wants to get the current weather in a city, and if so, the chatbot will use the get_weather() function to respond appropriately.

      Step 3 — Creating the Chatbot

      In the previous two steps, you installed spaCy and created a function for getting the weather in a specific city. Now, you will create a chatbot to interact with a user in natural language using the weather_bot.py script.

      You’ll write a chatbot() function that compares the user’s statement with a statement that represents checking the weather in a city. To make this comparison, you will use the spaCy similarity() method. This method computes the semantic similarity of two statements, that is, how similar they are in meaning. This will help you determine if the user is trying to check the weather or not.

      To begin, open the script:

      Then, import spaCy and load the English language model:

      ~/weather_bot.py

      import spacy
      import requests
      
      nlp = spacy.load("en_core_web_md")
      
      . . .
      
      

      After the get_weather() function in your file, create a chatbot() function representing the chatbot that will accept a user’s statement and return a response.

      Following your definition, add the highlighted code to create tokens for the two statements you’ll be comparing. Tokens are the different meaningful segments of a statement, like words and punctuation. This is necessary to allow spaCy to compute the semantic similarity:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
      

      Here the weather and statement variables contain spaCy tokens as a result of passing each corresponding string to the nlp() function.

      Save and close your file.

      Next you’ll be introducing the spaCy similarity() method to your chatbot() function. The similarity() method computes the semantic similarity of two statements as a value between 0 and 1, where a higher number means a greater similarity. You need to specify a minimum value that the similarity must have in order to be confident the user wants to check the weather.

      For example, if you check the similarity of statements 2 and 3 with statement 1 following, you get:

      1. Current weather in a city
      2. What is the weather in London? (similarity = 0.86)
      3. Peanut butter and jelly (similarity = 0.31)

      To try this for yourself, open the Python interpreter:

      Next, import spaCy and load the English-language model:

      >>> import spacy
      >>> nlp = spacy.load("en_core_web_md")
      

      Now let’s create tokens from statements 1 and 2:

      >>> statement1 = nlp("Current weather in a city")
      >>> statement2 = nlp("What is the weather in London?")
      

      Finally, let’s obtain the semantic similarity of the two statements:

      >>> print(statement1.similarity(statement2))
      

      You will receive a result like this:

      Output

      0.8557684354027663

      Setting a low minimum value (for example, 0.1) will cause the chatbot to misinterpret the user by taking statements (like statement 3) as similar to statement 1, which is incorrect. Setting a minimum value that’s too high (like 0.9) will exclude some statements that are actually similar to statement 1, such as statement 2.

      We will arbitrarily choose 0.75 for the sake of this tutorial, but you may want to test different values when working on your project.

      Let’s add this value to the script. First, open the file:

      Then add the following highlighted code to introduce the minimum value:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      

      Now check if the similarity of the user’s statement to the statement about the weather is greater than or equal to the minimum similarity value you specified. Add the following highlighted if statement to check this:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          pass
      

      The final step is to extract the city from the user’s statement so you can pass it to the get_weather() function to retrieve the weather from the API call. Add the following highlighted for loop to implement this:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
      

      To do this, you’re using spaCy’s named entity recognition feature. A named entity is a real-world noun that has a name, like a person, or in our case, a city. You want to extract the name of the city from the user’s statement.

      To extract the city name, you get all the named entities in the user’s statement and check which of them is a geopolitical entity (country, state, city). To do this, you loop through all the entities spaCy has extracted from the statement in the ents property, then check whether the entity label (or class) is “GPE” representing Geo-Political Entity. If it is, then you save the name of the entity (its text) in a variable called city.

      You also need to catch cases where no city was entered by adding an else block:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
            else:
              return "You need to tell me a city to check."
      

      Now that you have the city, you can call the get_weather() function:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
            else:
              return "You need to tell me a city to check."
      
          city_weather = get_weather(city)
          if city_weather is not None:
            return "In " + city + ", the current weather is: " + city_weather
          else:
            return "Something went wrong."
        else:
          return "Sorry I don't understand that. Please rephrase your statement."
      

      Recall that if an error is returned by the OpenWeather API, you print the error code to the terminal, and the get_weather() function returns None. In this code, you first check whether the get_weather() function returns None. If it doesn’t, then you return the weather of the city, but if it does, then you return a string saying something went wrong. The final else block is to handle the case where the user’s statement’s similarity value does not reach the threshold value. In such a case, you ask the user to rephrase their statement.

      Having completed all of that, you now have a chatbot capable of telling a user conversationally what the weather is in a city. The difference between this bot and rule-based chatbots is that the user does not have to enter the same statement every time. Instead, they can phrase their request in different ways and even make typos, but the chatbot would still be able to understand them due to spaCy’s NLP features.

      Let’s test the bot. Call the chatbot() function and pass in a statement asking what the weather is in a city, for example:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
      
      . . .
      
      response = chatbot("Is it going to rain in Rome today?")
      print(response)
      

      Save and close the file, then run the script in your terminal:

      You will receive output similar to the following:

      Output

      In Rome, the current weather is: clear sky

      You have successfully created an intelligent chatbot capable of responding to dynamic user requests. You can try out more examples to discover the full capabilities of the bot. To do this, you can get other API endpoints from OpenWeather and other sources. Another way to extend the chatbot is to make it capable of responding to more user requests. For this, you could compare the user’s statement with more than one option and find which has the highest semantic similarity.

      Conclusion

      You have created a chatbot that is intelligent enough to respond to a user’s statement—even when the user phrases their statement in different ways. The chatbot uses the OpenWeather API to get the current weather in a city specified by the user.

      To further improve the chatbot, you can:



      Source link

      How To Get Started With the Requests Library in Python


      Introduction

      In many web apps, it’s normal to connect to various third-party services by using APIs. When you use these APIs you can get access to data like weather information, sports scores, movie listings, tweets, search engine results, and pictures. You can also use APIs to add functionality to your app. Examples of these are payments, scheduling, emails, translations, maps, and file transfers. If you were to create any of those on your own it would take a ton of time, but with APIs, it can take only minutes to connect to one and access its features and data.

      In this article, we’ll learn about the Python Requests library, which allows you to send HTTP requests in Python.

      And since using an API is sending HTTP requests and receiving responses, Requests allows you to use APIs in Python. We’ll demonstrate the use of a language translation API here so you can see an example of how it works.

      Quick Overview of HTTP Requests

      HTTP requests are how the web works. Every time you navigate to a web page, your browser makes multiple requests to the web page’s server. The server then responds with all the data necessary to render the page, and your browser then actually renders the page so you can see it.

      The generic process is this: a client (like a browser or Python script using Requests) will send some data to a URL, and then the server located at the URL will read the data, decide what to do with it, and return a response to the client. Finally, the client can decide what to do with the data in the response.

      Part of the data the client sends in a request is the request method. Some common request methods are GET, POST, and PUT. GET requests are normally for reading data only without making a change to something, while POST and PUT requests generally are for modifying data on the server. So for example, the Stripe API allows you to use POST requests to create a new charge so a user can purchase something from your app.

      Note: This article will cover GET requests, because we won’t be modifying any data on a server.

      When sending a request from a Python script or inside a web app, you, the developer, gets to decide what gets sent in each request and what to do with the response. So let’s explore that by first sending a request to Scotch.io and then by using a language translation API.

      Install Python Requests

      Before we can do anything, we need to install the library. So let’s go ahead and install requests using pip. It’s a good idea to create a virtual environment first if you don’t already have one.

      Our First Request

      To start, let’s use Requests for requesting the Scotch.io site. Create a file called script.py and add the following code to it. In this article, we won’t have much code to work with, so when something changes you can just update the existing code instead of adding new lines.

      script.py

      import requests
      
      res = requests.get('https://scotch.io')
      
      print(res)
      

      So all this code is doing is sending a GET request to Scotch.io. This is the same type of request your browser sent to view this page, but the only difference is that Requests can’t actually render the HTML, so instead you will just get the raw HTML and the other response information.

      We’re using the .get() function here, but Requests allows you to use other functions like .post() and .put() to send those requests as well.

      You can run it by executing the script.py file.

      And here’s what you get in return:
      script run with output of `Response 200`

      Status Codes

      The first thing we can do is check the status code. HTTP codes range from the 1XX to 5XX. Common status codes that you have probably seen are 200, 404, and 500.

      Here’s a quick overview of what each status code means:

      • 1XX - Information
      • 2XX - Success
      • 3XX - Redirect
      • 4XX - Client Error (you made an error)
      • 5XX - Server Error (they made an error)

      Generally, what you’re looking for when you perform your own requests are status codes in the 200s.

      Requests recognizes that 4XX and 5XX status codes are errors, so if those status codes get returned, the response object from the request evaluates to False.

      You can test if a request responded successfully by checking the response for truth. For example:

      script.py

      if res:
          print('Response OK')
      else:
          print('Response Failed')
      

      The Response 200 output with a follow up of Response OK

      The message “Response Failed” will only appear if a 400 or 500 status code returns. Try changing the URL to some nonsense to see the response fail with a 404.

      You can take a look at the status code directly by adding:

      script.py

      print(res.status_code)
      

      This will show you the status code directly so you can check the number yourself.

      Failure output with 404

      Another thing you can get from the response are the headers. You can take a look at them by using the headers dictionary on the response object.

      script.py

      print(res.headers)
      

      output with headers printed in standard out

      Headers are sent along with the request and returned in the response. Headers are used so both the client and the server know how to interpret the data that is being sent and received in the response/response.

      We see the various headers that are returned. A lot of times you won’t need to use the header information directly, but it’s there if you need it.

      The content type is usually the one you may need because it reveals the format of the data, for example HTML, JSON, PDF, text, etc. But the content type is normally handled by Requests so you can access the data that gets returned.

      Response Text

      And finally, if we take a look at res.text (this works for textual data, like a HTML page like we are viewing) we can see all the HTML needed to build the home page of Scotch. It won’t be rendered, but we see that it looks like it belongs to Scotch. If you saved this to a file and opened it, you would see something that resembled the Scotch site. In a real situation, multiple requests are made for a single web page to load things like images, scripts, and stylesheets, so if you save only the HTML to a file, it won’t look anything like what the Scotch.io page looks like in your browser because only a single request was performed to get the HTML data.

      script.py

      print(res.text)
      

      Printed HTML data on the command line

      Using the Translate API

      So now let’s move on to something more interesting. We’ll use the Yandex Translate API to perform a request to translate some text to a different language.

      To use the API, first you need to sign up. After you sign up, go to the Translate API and create an API key. Once you have the API key, add it to your file as a constant. Here’s the link where you can do all those things: https://tech.yandex.com/translate/

      script.py

      API_KEY = 'your yandex api key'
      

      The reason why we need an API key is so Yandex can authenticate us every time we want to use their API. The API key is a lightweight form of authentication, because it’s added on to the end of the request URL when being sent.

      To know which URL we need to send to use the API, we can look at the documentation for Yandex.

      If we look there, we’ll see all the information needed to use their Translate API to translate text.

      Request syntax for using the API

      When we see a URL with ampersands (&), question marks (?), and equals signs (=), you can be sure that the URL is for GET requests. Those symbols specify the parameters that go along with the URL.

      Normally things in square brackets ([]) will be optional. In this case, format, options, and callback are optional, while the key, text, and lang are required for the request.

      So let’s add some code to send to that URL. You can replace the first request we created with this:

      script.py

      url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'
      res = requests.get(url)
      

      There are two ways we can add the parameters. We can either append it to the end of the URL directly, or we can have Requests do it for us. To do the latter, we can create a dictionary for our parameters. The three items we need are the key, the text, and the language. Let’s create the dictionary using the API key, 'Hello' for the text, and 'en-es' as the lang, which means we want to translate from English to Spanish.

      If you need to know any other language codes, you can look here. You are looking for the 639-1 column.

      We create a params dictionary by using the dict() function and passing in the keys and values we want in our dictionary.

      script.py

      params = dict(key=API_KEY, text='Hello', lang='en-es')
      

      Now we take the parameters dictionary and pass it to the .get() function.

      script.py

      res = requests.get(url, params=params)
      

      When we pass the parameters this way, Requests will go ahead and add the parameters to the URL for us.

      Now let’s add a print statement for the response text and view what gets returned in the response.

      script.py

      print(res.text)
      

      output dictionary with the values inputted

      We see three things. We see the status code, which is exactly the same status code of the response itself, we see the language that we specified, and we see the translated text inside of the list. So you should see 'Hola' for the translated text.

      Try again with en-fr as the language code, and you should see 'Bonjour' in the response now.

      script.py

      params = dict(key=API_KEY, text='Hello', lang='en-fr')
      

      French translated text

      Let’s take a look at the headers for this particular response.

      script.py

      print(res.headers)
      

      Headers printed in output

      Obviously the headers should be different because we’re communicating with a different server, but in this case the content type is application/json instead of text/html. What this means that the data can be interpreted as JSON.

      When application/json is the content type of the response, we are able to have Requests convert the response to a dictionary and list so we can access the data easier.

      To have the data parsed as JSON, we use the .json() method on the response object.

      If you print it, you’ll see that the data looks the same, but the format is slightly different.

      script.py

      json = res.json()
      print(json)
      


      The reason why it’s different is because it’s no longer plain text that you get from res.text. This time it’s a printed version of a dictionary.

      Let’s say we want to access the text. Since this is now a dictionary, we can use the text key.

      script.py

      print(json['text'])
      


      And now we only see the data for that one key. In this case we are looking at a list of one item, so if we wanted to get that text in the list directly, we can access it by the index.

      script.py

      print(json['text'][0])
      

      "Bonjour" without the square brackets

      And now the only thing we see is the translated word.

      So of course if we change things in our parameters, we’ll get different results. Let’s change the text to be translated from Hello to Goodbye, change the target language back to Spanish, and send the request again.

      script.py

      params = dict(key=API_KEY, text='Goodbye', lang='en-es')
      

      "Adios" printed to output
      Try translating longer text in different languages and see what responses the API gives you.

      Translate API Error Cases

      Finally, we’ll take a look at an error case. Everything doesn’t always work, so we need to know when that happens.

      Try changing your API key by removing one character. When you do this your API key will no longer be valid. Then try sending a request.

      If you take a look at the status code, this is what you get:

      script.py

      print(res.status_code)
      

      403 error
      So when you are using the API, you’ll want to check if things are successful or not so you can handle the error cases according to the needs of your app.

      Conclusion

      Here’s what we learned:

      • How HTTP requests work
      • The various status codes possible in a response
      • How to send requests and receive responses using the Python Requests library
      • How to use a language translation API to translate text
      • How to convert application/JSON content responses to dictionaries

      If you want to do more, check out this list to see different APIs that are available, and try to use them with Python Requests.



      Source link