Hướng dẫn how to convert python file to api - làm thế nào để chuyển đổi tệp python thành api

Ở đây tôi có một tập lệnh chuyển đổi PDF đến PDF. Làm thế nào tôi có thể sửa đổi nó để hoạt động như một API REST?

import os
import comtypes.client
SOURCE_DIR = 'D:/projects/python'
TARGET_DIR = 'D:/projects/python'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'ratesheet.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'ratesheet.pdf')
doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()
app.Quit()

Melebius

5,8704 Huy hiệu vàng35 Huy hiệu bạc49 Huy hiệu đồng4 gold badges35 silver badges49 bronze badges

Đã hỏi ngày 3 tháng 9 năm 2018 lúc 15:19Sep 3, 2018 at 15:19

Hướng dẫn how to convert python file to api - làm thế nào để chuyển đổi tệp python thành api

1

Bạn có thể sử dụng khung nghỉ nhẹ của Python Bình để làm cho chương trình của bạn có thể truy cập được cho các cuộc gọi REST. Kiểm tra hướng dẫn này: http://flask.pocoo.org/docs/1.0/tutorial/

Ở đó, bạn có thể chỉ cần nhận đầu vào tệp ở định dạng POST và một khi tệp được chuyển đổi, hãy gửi liên kết có thể tải xuống đến người dùng cuối. Bạn phải điều chỉnh mã này tôi đã viết với một người bạn cho các mục đích tương tự:

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)

Đã trả lời ngày 3 tháng 9 năm 2018 lúc 15:35Sep 3, 2018 at 15:35

Hướng dẫn how to convert python file to api - làm thế nào để chuyển đổi tệp python thành api

Hướng dẫn này trình bày cách triển khai chức năng Python tùy ý như một API với Bluemix và Flask - hoàn chỉnh với tài liệu API Swagger rõ ràng, trực quan. Hàm Python của chúng tôi sẽ là một triển khai đơn giản vào sàng của Eratosthenes, có một tham số số nguyên

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
0 và trả về tất cả các số nguyên tố
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
1 sao cho
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
2.

Trong khi hoàn thành hướng dẫn này, bạn sẽ:

  • Tạo một thuật toán (hoặc một số hàm tùy ý) bằng cách sử dụng máy tính xách tay trong DSX
  • Tồn tại chức năng
  • Phát triển API RESTful với tài liệu Swagger bằng bình
  • Triển khai API của bạn thành Bluemix

Thực hiện sàng lọc của Eratosthenes

Đầu tiên, chúng tôi sẽ cần tạo một thư mục sẽ chứa tất cả các tệp cần thiết cho ứng dụng của chúng tôi. Tôi sẽ đặt tên cho tôi

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
3.

!mkdir sieve

Thay đổi thành thư mục đó và chúng tôi sẽ bắt đầu.

cd sieve

Mây của Eratosthenes là một sàng số nguyên tố cổ xưa, gần như tìm thấy tất cả các số nguyên tố lên đến một giới hạn trên nhất định bởi các bội số nổi bật từ danh sách các số nguyên tố ứng cử viên. Thuật toán trông như thế này:

Hãy để viết các chức năng trong Python thuần túy. Việc thực hiện chính xác không phải là trọng tâm của bài viết này, nhưng thật tuyệt khi suy nghĩ.

def Eratosthenes(upper_bound):
prime = [True] * upper_bound
for p in range(3, upper_bound, 2):
if p > (upper_bound**.5):
break
if prime[p]==True:
for i in range(p * p, upper_bound, 2 * p):
prime[i] = False
return [2] + [p for p in range(3, upper_bound, 2) if
prime[p]]

Testing,

Eratosthenes(22) 
# [2, 3, 5, 7, 11, 13, 17, 19]

Chúng ta có thể sử dụng một số phép thuật Jupyter tích hợp để viết các tập tin. Chúng tôi sẽ đặt chức năng của chúng tôi trong tệp này để sử dụng sau trong ứng dụng. Bạn có thể xác định nhiều chức năng như bạn thích trong tệp này.

Để viết, chỉ cần chuẩn bị cho dòng này vào ô mã mà chúng tôi muốn viết

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
4

Chúng tôi sẽ đặt tên cho

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
5 này.

%%writefile prime_sieve.py
def Eratosthenes(upper_bound):
prime = [True] * upper_bound
for p in range(3, upper_bound, 2):
if p > (upper_bound**.5):
break
if prime[p]==True:
for i in range(p * p, upper_bound, 2 * p):
prime[i] = False
return [2] + [p for p in range(3, upper_bound, 2) if
prime[p]]

Chúng tôi sẽ lưu chức năng này vào một tệp, vì vậy chúng tôi có thể sử dụng nó sau.

Phát triển API RESTful

Chúng tôi sẽ sử dụng một vài công cụ để phát triển API, như Cloud Foundry và Flask. Phần này của hướng dẫn là một bản mở rộng của một hướng dẫn trước đây. Từ trong một cuốn sổ tay, chúng ta có thể viết các tệp và thực thi các lệnh shell, điều đó có nghĩa là chúng ta có thể phát triển ứng dụng hoàn toàn trong máy tính xách tay DSX.

%%writefile my_flask_app.py 
from flask import Flask, Response, jsonify
from flask_restplus import Api, Resource, fields, reqparse
from flask_cors import CORS, cross_origin import os
# the app
app = Flask(__name__)
CORS(app)
api = Api(app, version='1.0', title='APIs for Python Functions', validate=False) ns = api.namespace('primality', 'Returns a list of all primes below a given upper bound')
# load the algo
from prime_sieve import Eratosthenes as algo
''' We import our function `Erasosthenes` from the file prime_sieve.py. You create all the classes and functions that you want in that file, and import them into the app. ''' # model the input data
model_input = api.model('Enter the upper bound:', { "UPPER_BOUND": fields.Integer(maximum=10e16)})
# the input data type here is Integer. You can change this to whatever works for your app. # On Bluemix, get the port number from the environment variable PORT # When running this app on the local machine, default to 8080 port = int(os.getenv('PORT', 8080)) # The ENDPOINT
@ns.route('/sieve')
# the endpoint
class SIEVE(Resource):
@api.response(200, "Success", model_input)
@api.expect(model_input)
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('UPPER_BOUND', type=int)
args = parser.parse_args()
inp = int(args["UPPER_BOUND"])
result = algo(inp)
return jsonify({"primes": result})
# run if __name__ == '__main__': app.run(host='0.0.0.0', port=port, debug=False) # deploy with debug=False

Tài liệu hỗ trợ

Chúng tôi cần bao gồm một số tệp khác để API của chúng tôi hoạt động đúng khi chúng tôi cố gắng triển khai ứng dụng cho Bluemix. Những tệp này là:

  • import os
    from flask import Flask, request, redirect, url_for
    from werkzeug import secure_filename
    
    
    
    PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
    UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
    ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])
    
    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                _path = os.path.abspath("")
                uf = str(uuid.uuid4())
                # DO YOUR AMAZING STUFF HERE
                return redirect(url_for('index'))
        return """
        
        Upload new File
        

    Upload new File

    %s

    """ % "
    ".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
    6, điều này bao gồm thông tin cơ bản về ứng dụng của bạn, chẳng hạn như tên và bộ nhớ
  • import os
    from flask import Flask, request, redirect, url_for
    from werkzeug import secure_filename
    
    
    
    PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
    UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
    ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])
    
    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                _path = os.path.abspath("")
                uf = str(uuid.uuid4())
                # DO YOUR AMAZING STUFF HERE
                return redirect(url_for('index'))
        return """
        
        Upload new File
        

    Upload new File

    %s

    """ % "
    ".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
    7
  • import os
    from flask import Flask, request, redirect, url_for
    from werkzeug import secure_filename
    
    
    
    PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
    UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
    ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])
    
    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                _path = os.path.abspath("")
                uf = str(uuid.uuid4())
                # DO YOUR AMAZING STUFF HERE
                return redirect(url_for('index'))
        return """
        
        Upload new File
        

    Upload new File

    %s

    """ % "
    ".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
    8
  • import os
    from flask import Flask, request, redirect, url_for
    from werkzeug import secure_filename
    
    
    
    PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
    UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
    ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])
    
    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                _path = os.path.abspath("")
                uf = str(uuid.uuid4())
                # DO YOUR AMAZING STUFF HERE
                return redirect(url_for('index'))
        return """
        
        Upload new File
        

    Upload new File

    %s

    """ % "
    ".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
    9
  • !mkdir sieve
    0

Chúng tôi sẽ chạy những điều sau đây trong các ô khác nhau để tạo các tệp này.

%%writefile manifest.yml
--- applications:
- name: PRIMALITY_UNIQUE
- random-route: true
- memory: 256M
%%writefile Procfile
web: python my_flask_app.py
%%writefile README.md
"Getting Started with Python Algos on Bluemix"
%%writefile requirements.txt
Flask==0.11.1
cloudant==2.4.0
flasgger==0.6.4
Flask-Cors==3.0.2
Flask-RESTful==0.3.6
flask-restplus==0.9.2
gevent==1.2.1
%%writefile setup.py
""" Hello World app for deploying Python functions as APIs on Bluemix """
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='primality_test',
version='1.0.0',
description='Running Python apps on Bluemix', long_description=long_description,
url='https://github.com/IBM-Bluemix/python-hello-world-flask', license='Apache-2.0'
)
%%writefile LICENSE
"""Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ..."""

Triển khai để Bluemix

Bây giờ, chúng tôi sẽ triển khai ứng dụng cho IBM Bluemix. Để thực hiện điều này, bạn sẽ cần một tài khoản Bluemix. Để biết thêm thông tin về phần này của hướng dẫn, chúng tôi có một số tài liệu hữu ích về việc triển khai một ứng dụng sau khi nó được tạo.

Tại thời điểm này trong hướng dẫn, chúng tôi đã viết tất cả các tệp cần thiết cho ứng dụng của chúng tôi để chạy. Để triển khai với Bluemix (và giữ lại khả năng nhất khi gỡ lỗi, v.v.), tôi khuyên bạn nên sao chép cuốn sổ này và chạy tất cả các ô trước đó. Nếu bạn Naviagte đến

!mkdir sieve
1 và chọn
!mkdir sieve
2, điều này sẽ tự động xảy ra. Sau đó, trong thư mục cục bộ của bạn, bạn sẽ có tất cả các tệp cần thiết để tiến hành các bước tiếp theo này.

Một cách khác là tự tạo các tệp trên với trình soạn thảo văn bản yêu thích của bạn. Nếu đây là trường hợp, thì hãy loại bỏ các phép thuật

!mkdir sieve
3 khỏi đầu các ô mã.

Ok, hãy để triển khai ứng dụng này. Bạn sẽ cần sự quen thuộc cơ bản với dòng lệnh để có kết quả tốt nhất.

  • Cài đặt dòng lệnh Foundry Cloud. Dịch vụ nguồn mở này hoạt động với Bluemix để triển khai các ứng dụng.
  • Mở dấu nhắc thiết bị đầu cuối hoặc lệnh.

Mac - Nhấp vào biểu tượng Finder ở trên cùng bên phải, tìm kiếm thiết bị đầu cuối và mở đó

Linux - Phụ thuộc vào sự phân phối, nhưng bạn có thể biết nó ở đâu. Trong menu tìm kiếm các phụ kiện.

Windows - Nhấp vào nút Bắt đầu, tìm kiếm CMD, mở.

  • Đăng nhập vào Bluemix bằng cách chạy lệnh sau

!mkdir sieve
4

  • Nó sẽ nhắc nhở cho tên người dùng và mật khẩu của bạn.
  • Đẩy ứng dụng!

!mkdir sieve
5

Thay thế tên ứng dụng của bạn bằng tên ứng dụng trong tệp

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename



PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    
    Upload new File
    

Upload new File

%s

""" % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True)
6. Hãy chắc chắn rằng tên ứng dụng của bạn là duy nhất.

Bạn nên chạy

!mkdir sieve
7 để kiểm tra trạng thái ứng dụng của bạn.

Đó là nó!

Kiểm tra API

import requests

& đọc các tài liệu!

Nghiêm túc hơn, bạn đã tự tạo ra các tài liệu. Hãy xem bằng cách điều hướng đến URL.
Take a look by navigating to the url.

Hét lên với Snehal Gawas vì sự kiên nhẫn và hiểu biết của cô ấy về tài liệu này!

Làm cách nào để chuyển đổi Python thành API?

Nhập Convertapi Convertapi. api_secret = 'your-api-secret' ....
# Lưu tất cả các tệp kết quả vào kết quả thư mục. save_files ('/path/to/save/files') # Nhận chuyển đổi chi phí chuyển đổi_cost = result. ....
Kết quả = Convertapi. Chuyển đổi ('pdf', {'file': 'https: //website/my_file.docx'}) ....
Kết quả = Convertapi ..

Bạn có thể sử dụng Python cho API không?

Quá trình thực hiện các yêu cầu cho API với Python thực sự rất đơn giản, bạn chỉ cần biết API bạn muốn giao tiếp.Trong Python, bạn chỉ cần một dòng mã duy nhất để thực hiện cuộc gọi API cơ bản, điều này được thực hiện với hàm yêu cầu get ().. In Python you only need a single line of code to make a basic API call, this is done with the get() request function.

Làm cách nào để chuyển đổi tệp Python thành ứng dụng?

Chúng ta hãy từng bước để chuyển đổi tệp Python thành Windows có thể thực thi:..
Mở dấu nhắc lệnh, Việc chuyển đổi tập lệnh Python sang Windows thực thi được thực hiện bằng cách sử dụng dòng lệnh.....
Thay đổi vị trí thư mục - Sử dụng lệnh sau và hướng lời nhắc lệnh đến vị trí của mã Python của bạn:.

Làm cách nào để hiển thị mã python dưới dạng API REST?

Làm thế nào để tạo API RESTful bằng Python và bình..
Nhận tất cả các ngôn ngữ lập trình được lưu trữ trong API ..
Nhận một thể hiện cụ thể của ngôn ngữ lập trình ..
Lọc tài nguyên ngôn ngữ lập trình dựa trên trường Năm xuất bản ..
Đăng, đặt và xóa một thể hiện ngôn ngữ lập trình ..