Cannot invoke ngrok in python

336 Views Asked by At

I'm running flask in google colaboratory.

import os

html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>

Hello
<form action="{{ url_for('submit') }}" method="post">
    <textarea name="text"></textarea>
    <input type="submit">
</form>

</body>
</html>
"""

with open("pegasus/bin/evaluate.py"):
  if not os.path.isdir( "templates" ):
      os.makedirs( "templates" )
  with open("templates/index.html", mode='w') as f:
      f.write(html)

  from flask import Flask, render_template, request

  app = Flask(__name__)

  @app.route("/")
  def index():
      return render_template( "index.html" )

  @app.route('/submit', methods=['POST'])
  def submit():
      hello_eval()
      # request.formがユーザーの送信した文字列を保持するようになっている。
      return 'You entered: {}'.format(request.form['text'])

  if __name__ == '__main__':
      app.run(port=6006)

This is my flask code, and I want to access index.html in my browser. So I pasted a code for getting ngrok's url.

get_ipython().system_raw('./ngrok http 6006 &')
!curl -s http://localhost:4040/api/tunnels | python3 -c \
  "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

But the code throws an error.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I remember I ran it properly about 2 weeks ago. What can I do for that?

Help me!

1

There are 1 best solutions below

0
On

I solved the problem by changing python code like this.

import os
from flask_ngrok import run_with_ngrok
from flask import Flask, render_template, request

html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>

Hello
<form action="{{ url_for('submit') }}" method="post">
    <textarea name="text"></textarea>
    <input type="submit">
</form>

</body>
</html>
"""

app = Flask(__name__)
run_with_ngrok(app)

with open("pegasus/bin/evaluate.py"):
  if not os.path.isdir( "templates" ):
      os.makedirs( "templates" )
  with open("templates/index.html", mode='w') as f:
      f.write(html)


  @app.route("/")
  def index():
      return render_template( "index.html" )

  @app.route('/submit', methods=['POST'])
  def submit():
      hello_eval()
      # request.formがユーザーの送信した文字列を保持するようになっている。
      return "'You entered:' {}".format(request.form['text'])

  if __name__ == '__main__':
      app.run()