added api_bp.py and change in main.py #99

Closed
buya wants to merge 1 commits from Bug473-Buya into master
import json

from flask import Blueprint, session, jsonify

import pickle_idea2

path_prefix = '/var/www/wordfreq/wordfreq/'
path_prefix = './'  # comment this line in deployment

# 创建api蓝图
api_blue = Blueprint('api', __name__, url_prefix='/api')

def helper(res, result):
    for item in res:
        if type(res[str(item)]) == 'dict':
            helper(res[str(item)], result)
        if type(res[str(item)]) == 'list':
            for i in range(len(res[str(item)])):
                helper(res[str(item)][i], result)
        result.append(str(item))
    return result

@api_blue.route('/json/<username>', methods=['GET'])
def api_bp(username):
    # 获取session里的用户名,必须携带token
    token = session.get("token")
    if token == "70620F32A9DC965FCCF0447B674AA161":
        result = []
        user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username)
        s = pickle_idea2.load_record(user_freq_record)
        wordlist = helper(s, result)
        print(json.dumps(s))
        results = {}

        for word in wordlist:
            results[word] = len(s[word])

        return jsonify(results)

    else:
        print("无效的token")
        return jsonify({"error": "无效的token"})

At the beginning of the code, the necessary imports are included. These include the json module for working with JSON data and several modules from Flask, such as Blueprint for creating modular application structures, session for accessing user session data, and jsonify for converting Python objects to JSON responses.

We then creates a Flask blueprint named api_blue. Blueprints allow for organizing related routes and functionality in a modular way. The api_blue blueprint is configured to handle routes under the /api URL prefix.

Next, there is a helper function called helper. This function takes a dictionary-like structure res and a list result. It recursively traverses the dictionary, extracting keys and appending them to the result list. This function is later used to extract keys from a dictionary named s.

The main view function api_bp is defined and associated with the /json/ route within the api_blue blueprint. This function takes the username as a parameter, indicating that it expects this value to be included in the URL.

Within api_bp, the function retrieves the token value from the user's session using session.get("token"). It checks if the retrieved token matches a predefined valid token ("70620F32A9DC965FCCF0447B674AA161"). If the token is valid, the code within the if block is executed.

Within the if block, the function constructs a path to a frequency data pickle file based on the username. The pickle_idea2.load_record function is then used to load the data from the pickle file into a variable named s. This data represents the frequency records for the given username.

The helper function is called with the s dictionary and an initially empty result list. This extracts the keys from the s dictionary and stores them in a list named wordlist.

A dictionary named results is initialized as an empty dictionary. The code then iterates over each word in the wordlist. For each word, it retrieves the corresponding value from the s dictionary (which is a list of frequency data) and assigns the length of that list as the value in the results dictionary. In other words, it calculates the frequency count for each word.

Finally, the results dictionary is returned as a JSON response using the jsonify function. This function converts the Python dictionary into a JSON object and sets the appropriate response headers.

If the token is found to be invalid, the code within the else block is executed. It simply returns an error response as a JSON object with the key "error" set to the value "无效的token" (which means "Invalid token" in Chinese) using the jsonify function.

``` import json from flask import Blueprint, session, jsonify import pickle_idea2 path_prefix = '/var/www/wordfreq/wordfreq/' path_prefix = './' # comment this line in deployment # 创建api蓝图 api_blue = Blueprint('api', __name__, url_prefix='/api') def helper(res, result): for item in res: if type(res[str(item)]) == 'dict': helper(res[str(item)], result) if type(res[str(item)]) == 'list': for i in range(len(res[str(item)])): helper(res[str(item)][i], result) result.append(str(item)) return result @api_blue.route('/json/<username>', methods=['GET']) def api_bp(username): # 获取session里的用户名,必须携带token token = session.get("token") if token == "70620F32A9DC965FCCF0447B674AA161": result = [] user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) s = pickle_idea2.load_record(user_freq_record) wordlist = helper(s, result) print(json.dumps(s)) results = {} for word in wordlist: results[word] = len(s[word]) return jsonify(results) else: print("无效的token") return jsonify({"error": "无效的token"}) ``` At the beginning of the code, the necessary imports are included. These include the json module for working with JSON data and several modules from Flask, such as Blueprint for creating modular application structures, session for accessing user session data, and jsonify for converting Python objects to JSON responses. We then creates a Flask blueprint named api_blue. Blueprints allow for organizing related routes and functionality in a modular way. The api_blue blueprint is configured to handle routes under the /api URL prefix. Next, there is a helper function called helper. This function takes a dictionary-like structure res and a list result. It recursively traverses the dictionary, extracting keys and appending them to the result list. This function is later used to extract keys from a dictionary named s. The main view function api_bp is defined and associated with the /json/<username> route within the api_blue blueprint. This function takes the username as a parameter, indicating that it expects this value to be included in the URL. Within api_bp, the function retrieves the token value from the user's session using session.get("token"). It checks if the retrieved token matches a predefined valid token ("70620F32A9DC965FCCF0447B674AA161"). If the token is valid, the code within the if block is executed. Within the if block, the function constructs a path to a frequency data pickle file based on the username. The pickle_idea2.load_record function is then used to load the data from the pickle file into a variable named s. This data represents the frequency records for the given username. The helper function is called with the s dictionary and an initially empty result list. This extracts the keys from the s dictionary and stores them in a list named wordlist. A dictionary named results is initialized as an empty dictionary. The code then iterates over each word in the wordlist. For each word, it retrieves the corresponding value from the s dictionary (which is a list of frequency data) and assigns the length of that list as the value in the results dictionary. In other words, it calculates the frequency count for each word. Finally, the results dictionary is returned as a JSON response using the jsonify function. This function converts the Python dictionary into a JSON object and sets the appropriate response headers. If the token is found to be invalid, the code within the else block is executed. It simply returns an error response as a JSON object with the key "error" set to the value "无效的token" (which means "Invalid token" in Chinese) using the jsonify function.
buya added 1 commit 2023-06-15 07:10:09 +08:00

Better pull request exists. See Pull Request 93.

Better pull request exists. See Pull Request 93.
mrlan closed this pull request 2023-07-09 08:49:07 +08:00

Pull request closed

Sign in to join this conversation.
No reviewers
No Label
No Milestone
No project
No Assignees
2 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: mrlan/EnglishPal#99
There is no content yet.