elixir开发的项目_快乐的小项目:Elixir,Phoenix,Twilio和Spotify API

elixir开发的项目

by Nathan

通过内森

快乐的小项目:Elixir,Phoenix,Twilio和Spotify API (Happy Little Projects: Elixir, Phoenix, Twilio, and the Spotify API)

One of the most difficult aspects of starting a programming project is coming up with a project idea in the first place. No inspiration means no programming!

开始编程项目最困难的方面之一就是首先提出项目构想。 没有灵感就意味着没有编程!

Luckily, I recently discovered a project idea with a nice pacing to it: a basic Node.js and Express.js application using Spotify’s API and Twilio.

幸运的是,我最近发现了一个节奏不错的项目创意:一个使用Spotify API和Twilio的基本Node.js和Express.js应用程序。

If you’d like to follow along with the JavaScript version, check out this video. If you want to build it in Gradle and Spark, here’s Twilio’s original post.

如果您想了解JavaScript版本,请观看视频 。 如果您想在Gradle和Spark中构建它,请参阅Twilio的原始文章

For this article, we’ll build this app using Elixir and Phoenix. Let’s get started.

对于本文,我们将使用Elixir和Phoenix构建此应用程序。 让我们开始吧。

Here’s the general flow of the app:

这是应用程序的一般流程:

  • You text the title of a song to a Twilio number

    您将歌曲的标题发送到Twilio号
  • Twilio makes an HTTP POST to a preconfigured url with some infomation including the song title and information about the requester

    Twilio对预配置的URL进行HTTP POST,并提供一些信息,包括歌曲名称和有关请求者的信息
  • The application searches the Spotify API for the song, and parses out a preview url

    该应用程序在Spotify API中搜索歌曲,并解析出预览网址
  • The application dispatches a message to the Twilio API. This includes the number to call and a url to fetch some TwiML(Twilio Markup Language)

    该应用程序将消息调度到Twilio API。 这包括要拨打的电话号码和获取一些TwiML(Twilio标记语言)的网址
  • Twilio fetches the TwiML from our application, calls the recipient, and plays them the song preview.

    Twilio从我们的应用程序中获取TwiML,呼叫接收者,并向他们播放歌曲预览。

I’ve been through a majority of the curriculum at Free Code Camp. I helped design and build a large part of the core systems behind Free Code Camp, so I’m very comfortable with JavaScript. Following along with the presentation was easy, and I was quick to recreate it. The questions was, could I do it with a language and framework I didn’t have solid experience with?

我参加了Free Code Camp的大多数课程。 我帮助设计和构建了Free Code Camp背后的大部分核心系统,因此我对JavaScript非常满意。 跟随演示文稿很容易,我很快就重新创建了它。 问题是,我可以使用我没有扎实经验的语言和框架来做吗?

If you’d like to know what the finished product looks like, text the title of a song to +1 (334) 721–2652. Don’t worry, we won’t save your phone number or song. Request all the ABBA you want!

如果您想知道最终产品的外观 ,请将歌曲标题发短信至+1(334)721–2652。 不用担心,我们不会保存您的电话号码或歌曲。 请求所有您想要的ABBA!

NOTE: I’ve loaded some funds into this to keep it going a while. I’m hosting it on Heroku so it may take a moment to wake up and respond. If it doesn’t respond at all, the funds I added have been exhausted.

注意:我已经为此投入了一些资金,以保持一段时间。 我将其托管在Heroku上,因此可能需要一些时间才能唤醒并做出响应。 如果它根本不响应,则我添加的资金已用尽。

Here’s a short video of me interacting with my app using Google Voice.

这是我使用Google语音与我的应用进行交互的简短视频。

I wanted to challenged myself and play with a language that I’ve been smitten with since hearing about it. Elixir is a gorgeous language with Ruby inspired syntax. Elixir runs on the BEAM (Erlang VM), and is interoperable with Erlang. Yes, Erlang of WhatsApp fame. I love the idea of being able to tap into that kind of power and reliability. I also love functional programming.

我想挑战自己,并使用一种自听说以来一直迷恋的语言。 Elixir是一种华丽的语言,具有受Ruby启发的语法。 Elixir在BEAM(Erlang VM)上运行,并且可以与Erlang互操作。 是的, WhatsApp声名远播的 Erlang。 我喜欢能够利用这种功能和可靠性的想法。 我也喜欢函数式编程。

On top of Elixir, I’m also a fan of the Phoenix web framework. It’s easy to get started with, and easy to get things done in. The error messages are excellent and tend to tell you exactly how to fix them. Trust me on this, I’ve seen enough of them.

在Elixir之上,我还是Phoenix网络框架的粉丝。 它很容易上手,容易完成。错误消息非常出色,并且往往会告诉您确切的解决方法。 相信我,我已经看够了。

The first task is is to generate a new Phoenix application. I called mine Philter, so I typed:

第一个任务是生成一个新的Phoenix应用程序。 我打电话给我的Philter,所以我输入了:

mix phoenix.new philter --no-ecto --no-brunch

With this, we’re creating a new phoenix application called Philter, with no database layer and no JavaScript build system. We won’t be using any JavaScript in this project!

这样,我们将创建一个新的名为Philter的phoenix应用程序,它没有数据库层,也没有JavaScript构建系统。 我们将在此项目中不使用任何JavaScript!

Follow the on-screen instructions to finish setting up the application. We’re now ready to work through our list of tasks.

请按照屏幕上的说明完成应用程序的设置。 现在,我们准备完成任务列表。

特威里奥 (Twilio)

Twilio makes it pretty easy to setup an account. As an aside, their documentation and console are top notch. It’s one of my favorite web services to use.

Twilio使设置帐户变得非常容易。 顺便说一句,他们的文档和控制台是一流的。 这是我最喜欢使用的Web服务之一。

Sign up for Twilio here. If you want to follow along with this tutorial, you’ll have to add some funds. $5 would be more than enough to give you days of playing around. If you decide to follow along, buy a phone number and keep your browser tab open.

在此处注册Twilio。 如果要遵循本教程,则必须添加一些资金。 $ 5足够给您几天的游戏时间。 如果您决定继续使用,请购买电话号码并保持浏览器选项卡打开。

恩格罗克 (Ngrok)

The next service you’ll want to use is ngrok. This handy little service tunnels into a specified port on your computer and gives you a public url to use. The service is completely free, but I signed up for the $5/mo plan so I could have a reserved subdomain. It’s the little things, I tell ya.

您要使用的下一个服务是ngrok 。 这个方便的小服务通过隧道传送到您计算机上的指定端口,并为您提供一个公共URL以供使用。 该服务是完全免费的,但是我注册了$ 5 / mo的计划,因此可以保留一个子域。 我告诉你这是小事。

Open a new terminal tab and install ngrok via npm. Then use ngrok to specify that you’d like to create an http tunnel to port 4000 on your computer.

打开一个新的终端选项卡,并通过npm安装ngrok。 然后使用ngrok指定要在计算机上创建到端口4000的http隧道。

# is a comment for your information# ~ represents your terminal prompt~ npm i -g ngrok
...~ ngrok http 4000ngrok by @inconshreveable                           (Ctrl+C to quit)
Tunnel Status             onlineVersion                   2.1.1Region                    United States (us)Web Interface             http://127.0.0.1:4040Forwarding                http://someurl.ngrok.io -> localhost:4000Forwarding                https://someurl.ngrok.io -> localhost:4000

Now switch back to your original terminal tab and start your phoenix app.

现在切换回原始终端标签并启动phoenix应用程序。

~ iex -S mix phoenix.server      # <or>~ mix phoenix.server

The first option starts the server in an interactive shell that will let you interact with it. Regardless of your method of starting it, you’ll see it log out that it’s listening on your local machine on port 4000.

第一个选项在交互式外壳中启动服务器,使您可以与其交互。 无论使用哪种启动方法,您都将看到它注销,表明它正在侦听端口4000上的本地计算机。

Now open a new browser tab and visit localhost:4000 to confirm it’s working. Then, paste in the url from the Forwarding http line in the ngrok terminal that I bolded above. You’ll see your app there too. Magic!

现在打开一个新的浏览器选项卡,并访问localhost:4000确认其正常运行。 然后,从上面我加粗的ngrok终端的Forwarding http行中粘贴url。 您也将在那里看到您的应用程序。 魔法!

Go back to the tab you have your Twilio console open in, and find your phone number. Click on it, and you should see some configuration information. Under the messaging section, “When a message comes in”, enter the url from ngrok followed by “api/sms”. Ensure the HTTP method is set to POST. For reference, while building this application mine was set to http://tkb.ngrok.com/api/sms

返回到打开了Twilio控制台的选项卡,然后找到您的电话号码。 单击它,您应该看到一些配置信息。 在消息传递部分的“消息传入时”下,输入ngrok的网址,然后输入“ api / sms”。 确保将HTTP方法设置为POST。 作为参考,在构建此应用程序时,将其设置为http://tkb.ngrok.com/api/sms

While we have the Twilio console open, get your ACCOUNT SID and AUTH TOKEN credentials. You can find them by clicking on your account name in the top right hand corner of the window and looking at the “API Credentials” section. Create two environmental variables, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN. I use an extension of the preferences panel on my Mac called EnvPane. You can also search google and get a ton of results if you need help setting yours.

打开Twilio控制台后,获取您的ACCOUNT SID和AUTH TOKEN凭据。 您可以通过在窗口右上角单击您的帐户名称并查看“ API凭据”部分来找到它们。 创建两个环境变量TWILIO_ACCOUNT_SID和TWILIO_AUTH_TOKEN。 我在Mac上使用了“偏好设置”面板的扩展,称为EnvPane 。 如果您需要设置Google的帮助,也可以搜索Google并获得大量结果。

With all that information at hand, we’re nearly ready to tie it all together. We have one last thing to configure. We’re going to use ExTwilio, a library to help our phoenix application talk to Twilio.

有了所有这些信息,我们几乎准备将所有信息捆绑在一起。 我们还有最后一件事要配置。 我们将使用ExTwilio这个库来帮助我们的phoenix应用程序与Twilio对话。

Open config/config.exs and add the following above the final import statement:

打开config / config.exs并在最终import语句上方添加以下内容:

config :ex_twilio,  account_sid: System.get_env(“TWILIO_ACCOUNT_SID”),  auth_token: System.get_env(“TWILIO_AUTH_TOKEN”)

Here’s where we’re telling our application to read in these two environmental variables so we can send messages and make phone calls through Twilio’s API.

在这里,我们告诉应用程序读取这两个环境变量,以便我们可以通过Twilio的API发送消息并拨打电话。

In your favorite editor of choice (mine is Spacemacs), open your Phoenix application directory. Let’s get down to business.

在您喜欢的首选编辑器中(我的是Spacemacs ),打开Phoenix应用程序目录。 让我们转到工作上。

Open web/router.ex and get rid of any scope stuff you see. Replace it with:

打开web / router.ex并摆脱您看到的所有示波器内容。 替换为:

scope “/”, Philter do  pipe_through :browser
post “/twiml”, TwimlController, :indexend
scope “/api”, Philter do  pipe_through :api
post “/sms”, SmsController, :indexend

Replace any mention of Philter with whatever name you gave your application.

用您给应用程序提供的任何名称替换任何提及Philter的内容。

The above code did a few things. We have a created a route that will match POSTs to http://yourngrokurl/twiml and route to TwimlController’s index function. We also did the same for the http://yourngrokurl/api/sms route, passing off to SmsController’s index function. Learn more about routing in Phoenix by checking out the excellent documentation.

上面的代码做了几件事。 我们创建了一条路由,该路由会将POST与http:// yourngrokurl / twiml进行匹配,并路由至TwimlController的index函数。 我们还对http:// yourngrokurl / api / sms路由进行了同样的处理,并将其传递给SmsController的index函数。 通过查阅出色的文档,了解有关Phoenix中路由的更多信息。

Now create two files in the web/controllers/ directory, sms_controller.ex and twiml_controller.ex. Make your sms_controller.ex look like:

现在创建在web /控制器/目录,sms_controller.extwiml_controller.ex两个文件。 使您的sms_controller.ex看起来像:

defmodule Philter.SmsController do  use Philter.Web, :controller
alias Philter.Sms
def index(conn, %{"Body" => song, "From" => from, "To" => to}) do
Task.start_link(fn -> search_spotify(song, %{from: from, to:     to}) end)    send_resp(conn, 200, “”)   end
defp search_spotify(song, twilio_data) do    Philter.Spotify.search(song, twilio_data)  endend

To those Elixirists reading this, please keep in mind I’m still very much learning. With that disclaimer out of the way, on to a brief explanation.

对于那些阅读本文的药剂师,请记住我仍在学习中。 有了这个免责声明,我们来做一个简短的解释。

Twilio will post the phone number of the requester in a From field, our Twilio number in the To field, and the body of their text in the Body field. We’re fishing those out, then spawning a task to search the Spotify API.

Twilio将发布请求者的电话号码,在领域,我们的Twilio号在现场,他们的Body字段中正文中。 我们正在寻找那些,然后产生一个任务来搜索Spotify API。

Spawning a task executes some long running function in a super lightweight BEAM process. If something happens to the process, like it crashes or catches on fire or is stricken by cosmic rays, our application will happily continue accepting connections and prevent moments of developer panic.

生成任务会在超轻量级BEAM流程中执行一些长时间运行的功能。 如果该过程发生了某些事情,例如崩溃,着火或被宇宙射线撞击,我们的应用程序将很乐意继续接受连接并防止开发人员出现恐慌时刻。

A full discussion of Tasks and OTP in general is far beyond the scope of this article. Please refer to the Elixir links in this post if you’d like to learn more about this amazing beast.

通常,对任务和OTP的完整讨论远远超出了本文的范围。 如果您想了解更多关于这种神奇的野兽的信息,请参考这篇文章中的Elixir链接。

Now refer to the GitHub repository for this project. The files you’ll want to copy are lib/philter/spotify.ex and the entire lib/philter/spotify/ directory. Ensure you go through the files, changing any mention of Philter to your own application name. In spotify.ex, on line 55, replace “tkb” in the url to whatever your ngrok url is.

现在,请参考该项目的GitHub存储库 。 您要复制的文件是lib / philter / spotify.ex和整个lib / philter / spotify /目录。 确保浏览所有文件,并将对Philter的任何提及更改为您自己的应用程序名称。 在spotify.ex的 第55行中 ,将url中的“ tkb”替换为您的ngrok url。

Now make your twiml_controller.ex look like the following:

现在,使您的twiml_controller.ex如下所示:

defmodule Philter.TwimlController do  use Philter.Web, :controller
alias Philter.Twiml
def index(conn, %{"song" => song) do    render(conn, “index.html”, song: song)  endend

All we’re doing here is fishing the song out and and then passing it along as a variable to our template.

我们在这里所做的就是将歌曲捞出,然后将其作为变量传递给我们的模板。

Open the app.html.eex in the web/templates/ directory and delete everything except for:

web / templates /目录中打开app.html.eex并删除除以下内容以外的所有内容:

<%= render @view_module, @view_template, assigns %>

We don’t need any of that other markup!

我们不需要任何其他标记!

Next, create a file under the web/views/ directory called twiml_view.ex. We could put helper functions in here, but we don’t need any so it’s just going to live as a shell file. The contents should be:

接下来,在web / views /目录下创建一个文件twiml_view.ex 。 我们可以在这里放置辅助函数,但是我们不需要任何辅助函数,因此它将作为shell文件存在。 内容应为:

defmodule Philter.TwimlView do  use Philter.Web, :viewend

Now create a new directory under web/templates/ called twiml/ and inside of it create a file called index.html.eex. The contents are straightforward:

现在,在web / templates /下创建一个名为twiml /的新目录,并在其中创建一个名为index.html.eex的文件。 内容很简单:

<?xml version=”1.0" encoding=”UTF-8" ?> <Response>   <Say>Please enjoy the clip!&lt;/Say>   <Play><%= @song %></Play>   <Say>I hope you enjoyed your song clip</Say> </Response>

This is the response we’ll send to Twilio when they ask us for TwiML in response to our API interaction within the task I barely touched on. Feel free to play around, and reference the great TwiML documentation.

这是我们将在他们几乎未完成的任务中要求API交互时,当他们要求我们提供TwiML时,将发送给Twilio的响应。 随意玩耍,并参考出色的TwiML文档

With a restart of Phoenix, you should be able to text your Twilio phone number and get a phone call with the song preview!

重新启动Phoenix后,您应该可以给Twilio电话号码发短信,并可以通过歌曲预览功能拨打电话!

结局 (Dénouement)

I had a lot of fun implementing this little application with Elixir. Much like when I was learning JavaScript, I had to wrap my head around how to go about doing things, using functions correctly (even finding the correct functions to use!), and ensuring the application logic was correct.

使用Elixir来实现这个小应用程序,我获得了很多乐趣。 就像在学习JavaScript时一样,我不得不全神贯注于如何做事,正确使用函数(甚至找到要使用的正确函数!),并确保应用程序逻辑正确。

There were many furrowed brows and a lot of documentation and online tutorials were referenced as I dove deeper into Elixir. I was very pleasantly surprised at how little Phoenix specific code was needed though. It’s a great framework in my opinion.

当我深入研究Elixir时,有很多皱着眉头的地方,并且引用了许多文档和在线教程。 我对只需要很少的Phoenix特定代码感到非常惊喜。 我认为这是一个很好的框架。

In the end, the final product made the temporary frustrations worth it. Getting reactions out of my wife and friends like “That’s so cool!” or “You made that?” are definitely worth the effort. It also helped cement patterns and notions I had about how things worked more clearly. Maybe after I get out of the military, I will indeed be able to transition into a career in programming.

最后,最终产品使暂时的挫败感值得。 从我的妻子和朋友那里得到React,例如“太酷了!” 或“你做到了吗?” 绝对值得付出努力。 这也有助于巩固我对事情如何运作更加清晰的模式和观念。 也许在我退伍之后,我确实可以过渡到编程领域。

I have to give a shout out to Twilio. They’ve made an excellent project. Every interaction I needed to perform was well documented, and their management console itself made it easy to find what I needed and configure actions on that end.

我必须向特威里奥大喊大叫。 他们做了一个出色的项目。 我需要执行的每个交互都有详细的文档记录,并且它们的管理控制台本身可以轻松地找到我需要的内容并为此配置操作。

If you are interested in learning more about Elixir and Phoenix, I’d highly recommend Programming Elixir, Elixir In Action, and Programming Phoenix. I have all 3 and they are excellent! The online documentation is well above par, and more and more tutorials and articles are popping up. In general, the Elixir community is one of the best out there.

如果您有兴趣了解有关Elixir和Phoenix的更多信息,我强烈建议您编程ElixirElixir In ActionProgramming Phoenix 。 我所有的三个人都很出色! 联机文档远远超出了标准,并且弹出了越来越多的教程和文章。 通常,Elixir社区是那里最好的社区之一。

We are definitely excited to add Elixir to our backend languages at FreeCodeCamp.

我们很高兴在FreeCodeCamp上将Elixir添加到我们的后端语言中。

Learning to code is hard. I’d highly recommend signing up for FreeCodeCamp and following along the very structured and self-paced learning track we’ve established. Thousands upon thousands of people are finding success, and we have a massive community of helpful people - beginners to professionals - in our Gitter room.

学习编码很难。 我强烈建议您注册FreeCodeCamp,并按照我们已经建立的结构化和自定进度的学习轨迹进行学习。 成千上万的人正在寻找成功,我们在Gitter会议室中拥有大量乐于助人的社区-从初学者到专业人员。

Remember, don’t let something as ephemeral as frustration at a task today keep you from achieving your goals tomorrow. Happy coding!

请记住,不要让像今天这样的沮丧之类的短暂的事情使您明天无法实现目标。 编码愉快!

翻译自: https://www.freecodecamp.org/news/happy-little-projects-ef8cd157287/

elixir开发的项目

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值